How can I use user fields in panels title This seems to be basic but I cannot get my head around it and I am rather stuck. I am trying to have a panel override in D7 on the user profile page and access a few fields that I have defined in a user profile type (first name and surname in profile2)

I have added a context of the profile type in the panel and set the title to use the content pane title. I add the profile field, how can I set this field to be the panel title?

Any help welcome please.

Click on the gear icon on the grey bar for your field you have added, and click set as panel title.


Display unique text and button in nodes in a view in drupal 7 I have created a view listing 'invitation' nodes. When viewing each invitation on a full page, I have created a small block to allow people to RSVP to these invitations, but I would like to give them access to the button to RSVP directly from the view list.

Basically, if the user viewing the node in the list was invited to the event, something like this would show:

'You have been invited. RSVP here [button]'

Or if they have already RSVP'd:
'You are attending. Change your RSVP [button]'.

Any suggestions on how to do that?

A few more details:
- I created a custom module to handle the invitation process and form on a full view of the nodes. Details of invitations (who, where, when) are stored in a database.
- when the user is on the invitation in full view, i have created a block to display the RSVP form, adapting it to the status of the RSVP of the user.

Not quite sure if there's a module for that. Is Flags enough? In basic, it has a 0 or 1 option: respond and already attending.

And how to distinct users? I presume, users are logged in. Add a role to give certain users the privelege to see the RSVP-button/block/whatever.


How do I embed a node information/content into another node? I have two content types. One is author (fields are author name, designation, bio, image etc) and another one is article. In article content type, I have created an entity reference field "Author Info" where target bundle is author. While I am creating article, I get author list in Author Info field and I can select an author from the list.

When visiting the article page I only see the Author name/title under Author Info field. But I want to display there all author fields information.

I did some search to find out a way but no luck so far.

How I can do that?

Do you have any hint about that or what to search for?

Depending on your layout and other details there are a few ways to handle the display of the content from your related entity.

The most basic (and therefore limited) way is to go to Manage Display first on your article content type and adjust the settings for the format. It is likely already "rendered entity" (if not set that) and then click the gear to the right and set the view mode to be Default or Teaser. Once that's set, switch to manage the display of your authors and make sure the fields you want to display on your article pages are enabled.

The draw back to this approach is that it can have side effects unless you create extra view modes and are careful about when those modes are displayed.  For example, if you change the teaser settings any place the author teasers appear will change to match. If you install Display Suite you will have additional options to control the layout of both content types within the Manage Display form.

A common approach is to use views. With Views you can create a block that displays the author information, and then you can carefully place that block where ever you need. There is a reasonably good tutorial on Drupal.org for how to set something like this up in a general case.

If you'd like to do more research on options I suggest searching for things like "drupal views entity reference" or "drupal ds entity reference".


Contextual value when the filter is not available and PHP code I have block view that should be rendered in the node details page. i.e /node/*. The block should render latest 6 nodes published under the Category category_field that the node has its value.
However, the URL is rewritten and the category id tid is not available. The URL is looks like the following:
http://example.com/Category/world/the-node-title
So the contextual filter is not available in the URL. So, I created the following PHP code, shown in the screen shot, to get the category tid and return it:

In the node.tpl.php when I try to var_dump($node->field_category['und'][0]['tid']); it returns the number of tid of the current node. However, the above demonstrated code seems to be not work in the PHP filter code. When I try to return any available value for an category id such as 19 for example, it works.
In other words, how could I return the current node's category field id to the filter?

I found the cause of the problem from this resource and I have to define the $node variable by:

$node = node_load(arg(1));

Then I use the $node as shown in the question above.


Place or attach permanent file to the node edit form I want to make an attachment available for download to the user who is filling out a node edit form. This attachment will be a file template that they will fill out, save, then upload to the filefield field at some point, so I want the attachment to ALWAYS be available on the node edit form.

I realize I could do this by placing a block on the page via the block admin ui, but I would like to accomplish this using hook_form_alter, because the file that is attach will be specific to certain field within that form having certain values when a user is editing the form. I've provided a visual mock-up for further clarification.

If it's a PDF, you might also want to look into Fill PDF.


Is this the correct way to make a panels layout I have a 'working' panels layout that is getting the job done, but I'm unsure if it's the right way to do it.

Basically I copied the twocol_stacked layout from Panels and fitted it to my needs. The layout I'm looking for is this:

------------
|          |
|----------|
|  |       |
|  |       |
|  |-------|
|  |       |
|  |       |
------------

What shows up when in the panels lay out looks like this:

------------
|          |
|----------|
|  |       |
|  |       |
|----------|
|      |
|      |
--------

My css isn't too strong and I don't know if there is a way to make it display correctly in the panels layout window.  When I put some long text in the left side, it does push the lower div to the right the way I want, it just feels incomplete/wrong.

The css is mostly copied out of the twocol_stacked.css file with a few changes:

.panel-2col-stacked {
  /*  overflow: hidden;  */
  margin-top: 0;
  padding-top: 0;
}

.panel-2col-stacked .panel-col-top {
  width: 99.9%;
  clear: both;
}

.panel-2col-stacked .panel-col-top .inside {
  margin-bottom: .5em;
}

.panel-2col-stacked .panel-col-first {
  float: left;
  width: 33%;
}
* html .panel-2col-stacked .panel-col-first {
  width: 32.9%;
}

.panel-2col-stacked .panel-col-first .inside {
  margin: 0 .5em 1em 0;
}

.panel-2col-stacked .panel-col-last,
.panel-2col-stacked .panel-col-bottom{
  float: left;
  width: 66.9%;
}

.panel-2col-stacked .panel-col-last .inside {
  margin: 0 0 1em .5em;
}

.panel-2col-stacked .panel-separator {
  margin: 0 0 1em 0;
}

You can use Panels to create your own layout over at   /admin/structure/panels/layouts/add-flexible

This Video Tutorial covers on how to create one.

Basically, you add a column, and for each column you need to add a region. You can choose to use a flexible region or a fixed region, which you can resize by draging the grey bar.


I am unable to show the access denied message of the premium content module. How can I do this? I have 3 view modes (teaser, presentation and full view mode). I have created a node--content-type.tpl.php and created the code for each view mode using a conditional statement

if($teaser) {}
else if($node->type == 'tu_mooc' && $view_mode == 'presentation') {}
else {}

I have linked the 3 view modes. So I can go from the teaser to the presentation and from the presentation to the full view mode.

I have downloaded the premium content module so that access to the full view mode is limited to authenticated users. I made a small change in premium.module so that anonymous users have access to both the teaser view mode and the presentation view mode. The problem I have is that when I try to access the full view mode (as an anonymous user) I don't get the access denied message. Instead I get the code that appears within the teaser view mode. i.e. In node/1 I get the teaser of node1 instead of getting the access denied message.

Do I need to include some code like <?php print $denied_message; ?> into the node--content-type.tpl.php? or what do I need to do?

Thanks in advance.

I have included this code within the teaser in node--content-type.tpl.php:

<?php print $content['body'][0]['#markup']; ?>

And I have included this code in template.php:

function  mimooc_premium_body($arguments) {
  $node = $arguments['node'];
  node_build_content($node, 'teaser');
  unset($node->content['links']);
  $level = premium_level_load($node->premium);
  if ($level->denied_message) {
    $denied_message = $level->denied_message;
    $denied_message_format = $level->denied_message_format;
  }
  else {
    $denied_message = variable_get('premium_message', t('Full text available to premium subscribers only.'));
    $denied_message_format = variable_get('premium_format');
  }
  // Only display the premium message, if we actual have any content.
  if (!empty($node->content)) {
    return '

' . check_markup($denied_message, $denied_message_format) . '

' . l('Click here to sign in', 'user') . '

';
  }
}

Now, when I access the full view mode of the node, I get the teaser of that node with the access denied message.


How to get the value from the url in the function argument? When I pass nid value in the url like '/abc/[nid]', I want a function to receive that nid value

the code is as the following:

function ort_view_menu() {
          $items['ox_view'] = array(
            'title' => 'Viewed Details',
            'description' => 'g a report',
            'page callback' => 'abc',
            'type' => MENU_CALLBACK,
            'access callback' => TRUE,
           );
return $items;
}

function abc($nid) {
$rows = array();
$node = node_load($nid);
}

What changes do I need to make in hook_menu() to catch the nid value in the page callback function

What you are looking for is either:

arg() function:

  Returns a component of the current Drupal path.

  When viewing a page at the path "admin/structure/types", for example,
  arg(0) returns "admin", arg(1) returns "structure", and arg(2) returns
  "types".

or Callback Arguments:

function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_view',
      'page arguments' => array(1, 'foo'),
    );
    return $items;
  }

When path 'abc/def' is requested, the page callback function will get 'def' as the first argument and (always) 'foo' as the second argument.


localhost not showing /import If I navigate to http://localhost:8080/import I am taken back to the index page.

If I navigate to http://localhost:8080/?q=import I am take to the import page.

If I navigate to http://localhost:8080/admin I am taken to the list of admin options.

The webserver for localhost is the default one that comes with Phpstorm (in ubuntu 14.04), which is the built in webserver that comes with php5.4 and above.

When deployed to a remote server /import works.

What might cause this issue?

Just to eliminate a possible cause of your problem, and assuming your web server is Apache: make sure the mod_rewrite module is enabled. If it is not, then enable it and restart Apache.

To verify this, open the file httpd.conf inside your Apache installation folder and find the line starting with AllowOverride:

If that line looks like AllowOverride None

Then:

edit it to look like so: AllowOverride All
and afterwards restart Apache.

If you're using PHP Storm (as mentioned now in the further edited question), it might help to try what is documented in Disabling clean URLs. Here is a quote about that page:

  It's possible that a Drupal site that was once configured to run with clean URLs later on stops doing so. After that, almost all content is inaccessible, because the paths being generated are not supported by the hosting platform.


How to process more than one item from queue in each run? I have set up a queue using:

  function custom_logger_cron_queue_info()
  {
    $queues['custom_logger'] = array(
      'worker callback' => 'custom_logger_import',
      'time' => 60,
    );
    return $queues;
  }

Which I add items to using:

$item = array('uri' => $uri, 'uid' => $uid, 'fid' => $fid);
$queue = DrupalQueue::get('custom_logger');
$queue->createItem($item);

Which is working great, except that when cron runs every minute for this queue (I am using ultimate_cron module to set this) the custom_logger_import function is only processing one item per run. At present I have the function simply set up as:

function custom_logger_import($item) {
    $uri = $item['uri'];
    $uid = $item['uid'];
    $fid = $item['fid'];
//Do some stuff
}

Is there something I am missing on ensuring that as many items as possible get run? They are only small jobs that complete in less than a couple seconds but at the moment its taking 3-4 minutes to process just 3 items.

UPDATE:

The problem was actually in my function that was being called. I was using non-drupal friendly sql which seemed to prevent the job being done more than once. After updating all the database related stuff to drupal friendly database extraction layer stuff, it all works fine. For the record, here is a good way of checking that everything is running fine with the queues. Comment out your function being called by the queue and add this in replacement:

$file = '/somepath/hello.txt';
$current = file_get_contents($file);
$current .= $item['some variable from your queue item'] . " Hello\n";
file_put_contents($file, $current);

Then, when the queue is processed at cron, it should print out each of your queue items variable followed by hello to a text file.

The queue system is designed to process items until the time is up. Maybe it's a bug in Ultime Cron? Try running the default core cron.php to verify that.

Are you sure that you're actually adding multiple items to be processed? Check
your queue table.


Automated login with LDAP always returns error I have successfully setup LDAP module to authenticate users (and create new users). This is done through manual login form. Now I'm trying to enable automated single sign-on, but with no luck.

I have enabled LDAP SSO, and selected Turn on automated single sign-on.

On IIS, I've enabled Windows Authentication (Anonymous is still enabled).

I do not get automatically logged in, it returns error msg "You were not authenticated by the server. You may log in with your credentials below".

What else needs to be configured in a Windows environment to enable SSO?

Does anyone have any insight on what the reference info is talking about, when the say "This requires that you have operational NTLM or Kerberos authentication turned on for at least the path /user/login/sso, or for the whole domain" ? Other than looking at Windows Authentication on IIS, enabled providers = NTLM, what else needs configuring?

Perhaps not a direct answer to you question about the LDAP module but I managed to enable SSO in a Windows domain environment with the Webserver authentication (https://www.drupal.org/project/webserver_auth) module.

You need to force Windows Authentication in your IIS site and disable Anonymous authentication. The Webserver authentication module is also capable of creating accounts when a Windows Domain user is visiting your site and is not registered in Drupal.


Hide or disable field after registration I have 1 field on user registration page that should not be changed after account registration. It needs to be hidden or disabled.
Which module can do this ?

If you want to do it in custom module

my_module_form_user_profile_form_alter(&$form, &$form_state) {
  // Since it is on registration form, field might be reqruied.
  $form['your_field']['#required'] = FALSE;
  $form['your_field']['#access'] = FALSE;
}


Why does sql-sync fail? I'm managing Drupal 7 and Drupal 8 sites, so I'm running Drush 8 as that's the only version that can manage both. The Drupal 8 sites are installed using Composer and my local setup runs on MAMP 5.5.1.
It works fine for the Drupal 7 sites, and rsync works for the Drupal 8 sites as well. However, sql-sync fails. When I run drush sql-sync @local.dup @prod.dup, I get the following messages.

  Warning: require(/Users/username/path/to/local/vendor/bin/drush.php): failed to open stream: No such file or directory in /Users/username/path/to/localvendor/bin/drush on line 4
  Fatal error: require(): Failed opening required '/Users/username/path/to/local/vendor/bin/drush.php' (include_path='.:') in /Users/username/path/to/local/vendor/bin/drush on line 4
  The command could not be executed successfully (returned:                                                                                [error] Warning: require(/Users/username/path/to/local/vendor/bin/drush.php): failed to open stream: No such file or directory in /Users/username/path/to/local/vendor/bin/drush on line 4
  Fatal error: require(): Failed opening required '/Users/username/path/to/local/vendor/bin/drush.php' (include_path='.:') in  /Users/username/path/to/local/vendor/bin/drush on line 4, code: 255)
  The Drush sql-dump command did not report the path to the dump file produced. Try upgrading the version of Drush you are using on the source machine.

I get similar errors when checking drush @local status and drush @remote status as well as when I try to use the Drush 9 included in each site ( cd path/to/docroot > vendor/bin/drush @self @remote).

I've tried removing all Drush instances and installing only the same version that my host (cloudways) uses on the remote server (Drush 8.0.5) with no luck. I've installed Drush using CGR as instructed on Install (alternatives).
I've also checked my alias' file in the global Drush folder multiple times and can't find any issues.

What can I do from here to debug and resolve the issue?

I ended up running two global drush installs as explained here.

I needed to make to use same versions of Drush 9 both globally and on the site-specific installs to not get any errors. Now both Drush 8 and Drush 9 seem to run smoothly alongside each-other.


Disable language prefix for non-default languages I'm migrating a plain multilanguage HTML site to Drupal 7. One of the requirements of the migration is to preserve the current URLs of each page. Right now, the site has three languages and has URLs like these:
www.example.com/files/content1/es.html
www.example.com/files/content1/en.html

I've Internationalization and Pathauto modules enabled, and set the pattern for the node alias like this:
files/[node:title]/[node:language].html

However, the i18n module adds a prefix to the URL, like this:
www.example.com/es/files/content1/es.html
www.example.com/en/files/content1/en.html

In Language options, in Detection, I've enabled URL.
I've been able to remove the prefix for the default language, but I'm unable to remove it for the other languages. So, in the end, I have URLs like these:
www.example.com/files/content1/es.html
www.example.com/en/files/content1/en.html

How can I remove the prefix for the other languages too?

Thank you in advance!

Path redirection from old paths to new may be a solution (workarround really). This is compatible with SEO https://drupal.org/project/redirect


How to get a complete list of blocks that are active content on current page? I'm trying to get a full list of blocks that are active content on the current page. Preferably it would include details of what type of content is displayed in the block.
I need this information to display ads in the blocks. The ads need to be loaded through the javascript snippet, that I can place in the header (through drupal_add_js). But first I need to know if the block that contains the ad is active and that's why I need this list of blocks.
I'm using Drupal 7.

Follow the instruction to get the details of block for current page

In this template_preprocess_page function You can get a variable in that u have all region and it's block array
Using the above function we can get all the information of blocks note(if u want to see know the regions list see this function system_region_list


Installation profile glitch When I construct unattended installation using for instance:

drush site-install my_inst_profile \
  --account-mail='helpdesk@acme.com' \
  --account-name='siteadm' \
  --account-pass='sitepass' \
  --db-su='dbadm' \
  --db-su-pw='dbpass' \
  --db-url='mysql://drupal:drupal@mysqldb/drupal' \
  --locale='pl' \
  --site-mail='site@acme.com' \
  --site-name='MY Site' \
  --yes

and even the simplest possible installation profile my_inst_profile.info.yml, my_inst_profile.install and my_inst_profile.profile taken directly from How to write a Drupal 8 installation profile, the resulted installation is malfunctioning.

The symptoms are as follows:

Lack of the middle part of the GUI

No administrator role in the resulted system
Stark theme used as a default one even if info.yml file indicates any other theme.

It is relatively easy to handle 2 and 3 using:

drush role-create 'administrator'
drush config-set user.role.administrator is_admin true

and

drush pm-enable seven --yes
drush config-set system.theme admin seven --yes

respectively.
But the first one exceeds my Drupal capabilities.

There is some discussion and an issue queued on the net (see Adding translations to installation profile upon installation), but the proposals are no longer valid, as there is no /includes/locale.inc and even locale_add_language(), in Drupal 8.

Does anybody have any hints, on how to bring together ambition to use custom distribution with necessity to build localized site?

Addendum 1

Here is my_inst_profile.info.yml

name: my_inst_profile
type: profile
description: 'Installation profile dedicated for ACME company.'
core: 8.x

distribution:
  name: ACME Installation Profile

# Required modules
dependencies:
  - node
  - history
  - block
  - block_content
  - breakpoint
  - color
  - config
  - comment
  - contextual
  - contact
  - quickedit
  - help
  - image
  - options
  - path
  - taxonomy
  - dblog
  - search
  - shortcut
  - toolbar
  - field_ui
  - file
  - rdf
  - views
  - views_ui
  - editor
  - ckeditor

themes:
#  - bartik
  - seven
#  - stark

Here is my_inst_profile.install

<?php
/**
 * @file
 * Install, update and uninstall functions for the profilename install profile.
 */

/**
 * Implements hook_install().
 *
 * Perform actions to set up the site for this profile.
 *
 * @see system_install()
 */
function my_inst_profile_install() {
  // First, do everything in standard profile.
  include_once DRUPAL_ROOT . '/core/profiles/standard/standard.install';
  standard_install();

  // Can add code in here to make nodes, terms, etc.
}

Here is my_inst_profile.profile

<?php
/**
 * @file
 * Enables modules and site configuration for a standard site installation.
 */

use Drupal\Core\Form\FormStateInterface;

function my_inst_profile_form_install_configure_form_alter(&$form, FormStateInterface $form_state) {

  $form['site_information']['site_name']['#default_value'] = 'MY Site';
  $form['site_information']['site_mail']['#default_value'] = 'helpdesk@acme.com';
  $form['admin_account']['account']['name']['#default_value'] = 'siteadm';
  $form['admin_account']['account']['mail']['#default_value'] = 'helpdesk@acme.com';
  $form['regional_settings']['site_default_country']['#default_value'] = 'PL';
  $form['regional_settings']['date_default_timezone']['#default_value'] = 'Europe/Warsaw';

}

// Add any further custom code here like hook implementations.

As I mentioned at the beginning, this is just a starting point for further installation profile development.

Those are not bugs and have nothing to do with locale.

The standard install profile sets up the administrator role, the theme configuration and many other things, see standard_install() and its default configuration files like the overriden system.theme.yml.

I guess you mean the local tasks with "middle part of the GUI", that is a block and also set up by Standard, like many other blocks too.

If you create a new theme, it makes sense to look at standard on how it does things and copy the parts you need from it.


How to control editing access when node ownership keeps changing? I'm working on a project that involves group ownership and editing of nodes.  The rules that determine the visibility and editability of nodes are complicated, such that I'm having to roll my own node access code (that is, I couldn't find a module that would provide the kinds of control I need).

The following scenario is causing me some grief:

Alice and Bob are part of a group, and are working on node 123.  Node access entries exist that allow Alice and Bob to both edit the node under "normal" circumstances.
Alice edits node 123, and so becomes the "owner" of the node, in the sense that the uid field of the database entry for node 123 points to her.
Bob now edits node 123; he becomes the owner.
Alice, who has some degree of admin privileges in the group, takes the node private: She should be able to edit it, but Bob shouldn't.  "Taking the node private" means setting up some node access entries that are meant to deny access to the node to everyone but her.
However, since Bob is the most recent person to have edited the node, he's still the "owner of record", and node/123/edit is available to him, as a result of the standard node access rules regarding node ownership.  (This is how I'm thinking about it, anyway.)

Any ideas for how I can get around this, and keep Bob blocked from editing the node?  I've thought about:

adding some node_insert and node_update hooks that would force the uid of the node to always point to Alice; the node access entries would allow Bob to edit the node when he's supposed to be able to.  Might work, but this seems questionable/risky/horrifically hackish at best.
Maybe there's a hook that would reach down into the access system and let me test whether a request for node/123/edit should be permitted based on the current user and system state?

Any other possibilities out there?  Thanks!

See my recent answer here: https://drupal.stackexchange.com/a/55144/7153

But basically, you can use

nodeaccess_userreference

or

nodeaccess_nodereference

to acheive that access control functionality there.

Basically you could deny author access and control edit access with one multi-value reference field instead.

More info, including screenshots at first link.


Does drush have built-in variables or macros? Does drush have built-in or predefined variables or macros?

An example would be like the base directory of the Drupal installation, database name, passwords etc? Something like the values displayed in drush status

If you source the file examples/example.bashrc from your ~/.bashrc file, then you can do useful things like cd %root or cd @site:%root.  Without sourcing that file, you can use cd $(drush dd %root).  If you want to go to a module or theme directory, cd $(drush dd %devel) also works.  Using the %path aliases without qualifying them with a @site alias does, of course, require that your cwd be inside some Drupal site (or $options['root'] must be set in some drushrc.php file).


Load a block in template? Is it possible to load a block contents into a template file (say like page.tpl.php)? I need to extract a block which contains colophon (e.g. copyright and company information) and place it after the footer region.

Also, are there any performance problems with this approach?

Maybe I am missing something about your question, but it seems that one of three basic techniques should work for you.

If you just need information from a block in the footer, place the block in the footer region and style it with css so that it is positioned where you need it to be.
If you need to adjust the information in a block (e.g. to place a block on a page twice), use a render hook.  c.f. The Scary Render Array.
If you just want to put some custom content + php in your template after the footer, you can just plop it down there.  If you have code in your block function that needs to be called in two locations, factor it into its own function, and call it from the template and from the block function.

It feels wrong to call the block api from a template file when one of the above more conventional techniques should work just as well.


Modify Drupal error handler without killing kitten Drupal 6's common.inc file includes:

  // Set the Drupal custom error handler.
  set_error_handler('_drupal_error_handler');

If I'm following the logic correctly, this results in all PHP errors going to Watchdog (if enabled).

I'd like to continue using Watchdog (not syslog or similar modules) for everything but PHP errors. PHP errors should go to a file (i.e., the error_log that is configured in php.ini).

I'd prefer not to patch Drupal to remove its use of set_error_handler(), so I'm looking for some ideas. Perhaps I can make my own call to set_error_handler() in a hook_init() or settings.php? Any ideas?

Yes, you can use your own error handler instead. You'd put this in your own module - I'm not sure if you would need to put it earlier than hook_init(), though, i.e. in hook_boot(). Check out the Devel module, which has an option for overriding the error handler to make debugging easier.


What module controls Commerce Kickstart 2 add to cart popup? I have installed the demo store Commerce Kickstart 2. Going through and changing things here and there somehow I've affected the popup functionality. It no longer fires when adding something to your cart. I'm thinking I may have just turned off the module that controls this? Or maybe it's a setting I clicked off?

From Commerce Kickstart 7.x-2.0-rc3 and up, the module is Commerce add to cart confirmation
(Previously this functionality was a part of the base product feature and couldn't be disabled).


How do I retrieve values from a webform? I can see the values submitted in the $_POST, so I know they are there, but when I uses a submit handler to retrieve them, I get NULL. I'm fairly new to PHP so not sure if it's a simple syntax mistake or something more. Thanks.

function zendesk_forms_form_alter(&$form, &$form_state, $form_id){

  if ($form_id == 'webform_client_form_47') {

    $form['#submit'][] = "zendesk_forms_support_form_submit_handler";
  }
}

function zendesk_forms_support_form_submit_handler($form, &$form_state) {
  form');
  $ticket = array(
      'description' => $form_state['values']['description'],
      'subject' => $form_state['values']['subject'],
  );
  echo $ticket;

Try this:

$ticket = array(
  'description' => $form_state['values']['submitted']['description'],
  'subject' => $form_state['values']['submitted']['subject'],
);


Custom module to alter display value of field I have a question about custom modules. I am trying to write a module that changes the display value of a field. I think the thing I'm trying to do require a

hook_page_alter

method, and to change the field

$page['content']['system_main']['nodes'][$nid]['body']

So far I'm haven't been able to change anything on the page. Would anyone have a good solution?

The example you're using in the hook_page_alter() docs isn't a valid example but a demonstration. The problem here is the variable $nid isn't defined in your hook invocation. The expression:

$page['content']['system_main']['nodes'][$nid]['body']

isn't valid. $page['content']['system_main']['nodes'] contains an associated array of nid/node data.

This can be one or many nodes depending on the context (e.g. front page vs. a node page). You'll need build your logic accordingly (e.g. $nid = reset($page['content']['system_main']['nodes']) to retrieve the specific node that you want then make the altercation as you need it.


How to create a default value for an entity base field in Drupal 8 Both the Examples module and the Drupal Console generate:entity:content both have code like this:

$fields['first_name'] = BaseFieldDefinition::create('string')
  ->setLabel(t('First Name'))
  ->setDescription(t('The first name of the Contact entity.'))
  ->setSettings(array(
    'default_value' => '',
    'max_length' => 255,
    'text_processing' => 0,
  ))

I was thinking that if I provided 'default_value' => 'Fred' in place of 'default_value' => '' that I might affect the default value of the field. I would expect to have seen Fred when creating an entity of this type, and I might have expected to see Fred as the default value in the entity's table definition, but it's not there.

I'm learning D8 and so have two parts to this question really, the first is just how to provide a default value, the second is if this default_value key isn't it, what is it for?

The code is outdated, you should create a patch to fix it.

There is a new separate method for the default value, setDefaultValue().


Services Download API I am having difficulties setting up an endpoint with the services module to download a file. Ultimately I want the user to hit the services end point with something like /api/download/file/fid and it will download the file to the users machine. The reason I want to do it through services and not just get users to hit /sites/default/files/file.filetype is because I need to be able to restrict access to the download link with HTTP basic auth. I have tried searching but cannot find how to achieve this? any help is much appreciated.

EDIT:
My xml response when I imported arpitr's endpoint configuration and called it.

<result>
    <fid>6</fid>
    <uid>1</uid>
    <filename>Transition1.jpeg</filename>
    <uri>public://Transition1.jpeg</uri>
    <filemime>image/jpeg</filemime>
    <filesize>435007</filesize>
    <status>1</status>
    <timestamp>1475199010</timestamp>
    <type>image</type>
    <uuid>4c703ad2-290c-4573-9a29-a7e86e1a874e</uuid>
    <field_file_image_alt_text/>
    <field_file_image_title_text/>
    <rdf_mapping/>
    <metadata>
        <height>2304</height>
        <width>3072</width>
    </metadata>
    <alt/>
    <title/>
    <height>2304</height>
    <width>3072</width>
</result>

I am missing <file> which is the content of the file base 64 encoded, any idea why this could be?

You can send an image through resources using base64_encode(), or _file_resource_retrieve().

I don't remember the specifics of it all, but here is how I did it for Services in a project last year. You'll have to dissect the code yourself, but it definitely does work:

/**
 * Override of the Services module File resource, retrieve method.
 *
  * The original method does not allow for the retrieval of an image with an image style.
  * This override accepts an additional parameter, $image_style, which if set will return
  * the file data for the image in that image style. This allows for the retrieval of private files.
  *
  * @param $image_style
  *   If this value is set to an image style, the data for the image in that image style will be returned.
  *   Otherwise, the original File resource is invoked.
  *
  * @see _file_resource_retrieve()
  */
 function ba_api_file_retrieve($fid, $include_file_contents, $get_image_style, $image_style)
 {
    if($image_style)
    {
        if ($file = file_load($fid))
        {
            $filepath = $file->uri;

            if($image_style == 'raw')
            {
                $return = base64_encode(file_get_contents(drupal_realpath($filepath)));
            }
            else
            {
                $return = base64_encode(file_get_contents(drupal_realpath(image_style_path($image_style, $filepath))));
            }
        }
        else
        {
            $return = 'file not found';
        }
    }
    else
    {
        module_load_include('inc', 'services', 'resources/file_resource');

        $return = _file_resource_retrieve($fid, $include_file_contents, $get_image_style);
    }

    return $return;
 }


How to change modified date in a node when users votes more than 5 times? Mayday, mayday! :-) I have 2 views of nodes showing "published nodes" and "moderation nodes". I'm using vote_up_down in my nodes.

I want, when the users vote up a node more than 5 times, to modify the date of the node, and put it "now".

Can somebody tell me how I could do this?

Thanks.

Since vote_up_down uses voting API underneath, you can use the voting rules module to allow you to configure rules to fire when votes are made.

You could then make a rule that fires when a vote is made, that then checks the total number of votes for that node and if it has 5 votes update the nodes updated date and save.

So the event/trigger would be voting on the node, the condition would be that the node has 5 votes (after a quick look it is likely the "Evaluate the results of a vote on a ..." condition), and the action would be updating the modified/updated date of the node.


How to redirect after node insert (not form redirect)? I am trying to find out how to redirect after I insert a new node. All the answers I have been able to find discuss $form_state->setRedirectUrl(); but this is a form redirect; not a proper redirect after insertion.

The difference is that when I submit the node form; I use hook_node_insert to create another entity based on information from the node being inserted. After the parent node is inserted; I want to redirect to a path based on the entity id of the new child entity.

In hook_node_insert (for the parent; i.e. original form submit)) I set a drupal_register_shutdown_function which properly saves my child entity and I then have the ->id() of the new (child) entity.

I have seen various examples using RedirectResponse, such as this:

$redirect = new RedirectResponse(Url::fromUserInput('/admin/commerce/orders/' . $order->id() . '/payments')->toString());;
$redirect->send();

but none of these work.

EDIT

to try to line this up with @4k4's suggestion, this is where I am at:

function my_module_node_insert($node) {
  $s = \Drupal::service('sia_general.redirects');
  $s->createPolicyRedirect($node);
}

in my Service:

class RedirectServices implements EventSubscriberInterface {

  static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE] = ['gotoPolicy'];
    return $events;
  }

  public function createPolicyRedirect($policy) {
    $this->policy = $policy;
  }

  public function gotoPolicy(FilterResponseEvent $event) {
    // We only care if this happened after policy was created.
    if (!$this->policy) {
      return;
    }

    $redirect = new RedirectResponse(Url::fromUserInput('/node/' . $this->policy->id() . '/edit')->toString());;
    $event->setResponse($redirect);
  }
}

when the Policy node is created; the hook_node_insert is called, which in turn calls the createPolicyRedirect() service and passes the newly created Policy object. After this it returns to the event subscriber which originally called the function which created the Policy. After that it hits the final pass of gotoPolicy(); but $this->policy is not set at this point.

Just to test that the redirect response worked as i hope; i tried setting a SESSION var in createPolicyRedirect(); but even that isn't set once i get to final gotoPolicy call.

EDIT #2

Still no luck and guessing due to the event handler within event handler that i am doing... so more context.

The complete flow is as follows:

create App entity
this adds items to Commerce cart
admin adds payment
PaymentComplete handler "places" the Order
OrderComplete handler loads the App and sets a Workflows field and then saves  the App
during the App->save(), the change in Workflow triggers creating a Policy entity
this triggers my hook_node_insert($policy) (note: this is still within OrderComplete event handler).
in my insert hook i fire my 1st method above (which sets $this->policy)
i then return to finish the OrderComplete event handler
after the OrderComplete is finished; i hit my final run through the 2nd method (the KernelEvent); but by this time, $this->policy is no longer set.

My guess is that the ordercomplete does a page load before my kernel event is run (not sure that makes sense); so maybe this is a bug in Commerce; or at the very least i need to approach this differently, like alter what commerce is doing. Perhaps Drupal's event handling system isn't quite ready to handle situations this complex yet??

You could do a redirect in hook_node_insert(), however that would then prevent any other implementations of hook_node_insert() that come after your implementation from being executed.

I would instead suggest removing the code you've added in hook_node_insert(), and instead adding a custom submit handler to the node creation form. You can get the newly created node ID from $form_state->get('uid'). You can use that to load the newly created node, then create your node, and finally add the redirect in the form state, as you've mentioned in your post. This way no APIs are bypassed, and your redirect will happen after everything has been executed.


How can I get the Register form on the front page? I've managed to create a new theme, customize the front page pretty much how I wanted it, and I've encountered a problem.

I need to get the register form (create new account) in a pop-up on the front page.

After following the instructions from Form API in Drupal 8:

    <?php

/**
* @file
* Functions to support theming in the themename theme.
*/

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\UrlHelper;

/**
* Implements hook_preprocess_HOOK() for HTML document templates.
*/

function themename_preprocess_html(&$variables) {

$form = \Drupal::formBuilder()->getForm('Drupal\user\register');

return $form;
}

I can't figure out what I'm doing wrong, because I get an error saying that is not a valid form. I have also tried using the form id as a parameter, still no valid form.

Could anyone please help? I could use a working example.

The correct form id shoud be Drupal\user\RegisterForm. However, because the register form is attached to an entity, you can't use getForm directly. You need to create an entity and then get the register form for that entity.

The role of the preprocess function is to add / modify / delete template variables via the $variables parameter, so you need to add the form to that array rather than return it.

Something like this should work:

function themename_preprocess_page(&$variables) {
  $entity = \Drupal::entityManager()
    ->getStorage('user')
    ->create(array());

  $formObject = \Drupal::entityManager()
    ->getFormObject('user', 'register')
    ->setEntity($entity);

  $form = \Drupal::formBuilder()->getForm($formObject);
  $variables['register_form'] = $form;
}

Now you should be able to print the form via {{ login_form }} in the page.html.twig template.


How to give image instead of text in pager? I need to change the text in to image in pager.

For example:

<< First < Previous  4 5 6 7  Next > Last >>

Now instead of the above i need to print as below:

<< <  4 5 6 7  > >>

Note: Consider the less than and greater than symbol as images.

Here is the syntax :

theme_pager_next($text, $limit, $element = 0, $parameters = array())

Here is my code :

$li_next = theme('pager_next', theme_image(drupal_get_path("theme", "fluid") . "/images/text.gif"));

My output is as follows for the above code :

<img src="/sites/all/themes/fluid/images/text.gif" alt="" title="" width="7" height="13" />

But my desired output is to print the image which is in the image tag.

Any help will be thankful and grateful.

Thanks in advance.

See How to change text-links to image links in the pager.
By using the theme_image() function Drupal should nicely format the <img> tag, and output it to your theme. Well, this works, but unfortunately somewhere in this theme_pager() process a l() is telling Drupal to only output plain text here.

The trick here is not to rewrite your whole pager functions. Have a look at theme_pager_link(); this function is building all the links that are used by the pager functions. When you look closer to the l() formatting the output is done using the following code:

return l($text, $_GET['q'], array('attributes' => $attributes, 'query' => count($query) ? implode('&', $query) : NULL));

You'll see the options aren't setting the HTML output. So I placed the whole function in my template.php (changing theme_pager_link() to `landrush_pager_lin()k) with a different output:

return l($text, $_GET['q'], array('attributes' => $attributes, 'html' => TRUE, 'query' => count($query) ? implode('&', $query) : NULL));

Note 'html' => TRUE.

Now l() is allowing me to print HTML tags (images!) within the pager function.


User list view showing total nodes created for each user I have a view which displays a list of particular users. For each user displayed I would like to also display the total number of nodes that user has created.

I was wondering if there was an easy and/or efficient way of doing this, or if there is a module available that can? Obviously you would not want to calculate each total on the fly, but rather have the totals cached and updated whenever a user creates/deletes a node.

It would be nice if a module existed that could take care of this aggregate accumulation, and not just for node creation/deletion but for any desired aggregate (per user, or per node, etc).

Any help is greatly appre

If I understand the question this can be done in Views using aggregation.

Set up a View to list All Content (not users). Select Unsorted. Show fields rather than teasers.
Double check you really don't have any sorting in the Sort criteria section. If you do, it'll mess up the aggregation settings. If you forgot, remove it now. I know I'm repeating here, but if you don't do this you run the risk of driving yourself crazy wondering why aggregation doesn't seem to be doing what it's supposed to.
Add the Content: author relationship (in the Advanced section). This is so you can gain access to the the name field for the user.
Add the 'User: name' field (in the Fields section).
Turn on the Use aggregation option (in the Advanced section under Other).
Change the Aggregation settings for the Content: Title field. Set aggregation to COUNT. This will count up all titles authored by the same user.
If you need sorting, e.g. in descending number of posts, you can add that. But make sure under sorts you set the aggregation settings correctly, e.g. to COUNT. Alternatively, leave the Sort criteria section empty and sort via the Table format.

That's the tricky bit. If that's all working you can refine the output with Global: Custom Text fields or use of tables.

Your view configuration will look at bit like this:

Note: if you user entity has extra fields, e.g. for a richer user profile or for name variants etc. you may be able to access these through the 'Content: author' relationship. Or you may need to add another relationship.


Entity select Dropdown I'm working on a Drupal 8 view that is going to be a page.

How can I make an exposed entity filter a dropdown? The entity is not a content type, but rather a custom entity with it's own module.

I can't seem to find any documentation about it.

Views on Drupal 8 are slightly different, but you might consider this answer (given for Exposed filters with dropdown selections), which gives you a quick module way of creating a custom node-based exposed filter drop down for a Drupal 7 view. This is essentially what I would suggest for your use case.


Make one reference and load the other automatically (Entity Reference) I have a content type "songs", lets say a node has a reference to 4 or 5 other nodes.
What I want is when I create a new node, I just need to make a reference to one node and the other 4 nodes will be loaded automatically.

Is that possible?

Broadly if your node reference is required your user must to fill it on node creation. So you could try to use hook_node_presave or in the form layer you could have your submit handler to deal with that. Once you get the reference chosen by the user you would need to retrieve the other 4 related references that will be also added as siblings in the multi valued node reference field.
By another hand if you want to make all of this visible in the form before it gets submitted you could use hook_form_alter (in case you don't have your own hook_form) to add a behavior to the node reference field form element and if it has just a checkbox widget you could simply automatically check the other nodes to be referenced using the behavior to react the check box that has been checked.


Views PHP is outputting incorrectly I'm trying to work with Views PHP but for some reason something is going completely wrong. I have a content field called telephone. In this field is a number "06-12345678" now I want to use Views PHP to remove the "-" so I get the number "0612345678".

What I do is I make a view with the field Telephone and a Global: PHP field underneath it. In this Global: PHP field I add the following code to see if it is working.

<?php print $row->field_telephone; ?>

So when I save this field I get the output: "11" instead of 06-12345678.

When I try <?php print $row->field_title; ?> it does give me the suspected output..? What am I doing wrong? How can I solve this?

$data->field_field_telephone[0]['raw']['value'];

This will give you your value from that field in Views PHP. If you use dpm() from Devel module it will show you that $row->field_telephone is 11. that's the NID.

Try to avoid using Views PHP unless you are doing something too complex for views. And even then you should try to write a custom module to interact with views instead of saving code in the DB.


how to block internal Drupal paths for anonymous users? Is it possible to block internal Drupal paths for anonymous users and leave only paths generated by pathauto? For example:

block path: /taxonomy/term/5
leave path: /products/books

In google webmaster tools for my site, all taxonomy pages have an issue called "Pages with duplicate title tags" and google is showing both paths for each term, which is a problem. How to block the internal Drupal path for anonymous users?

By the way, apart from this, some taxonomy terms are purely for config and their paths should be blocked not because googlebot has a problem but generally, those paths make no sense for non-admins and should never be accessed directly via url.

If you have clean URLs enabled, and are using the Global Redirect module, the users should never actually see the default paths (sometimes also called the internal path).

If a user goes to node/123 or taxonomy/term/456, and a path alias exist, then they will get an HTTP 301 and then redirect the the path alias.  Google and won't index the paths that 301.

In addition, Drupal will add a rel='canonical' to the header, to notify the world about the offical URL.

However, if you ever had you site without Global Redirect enabled, then you could at one point access pages from multiple paths.  Once Google starts seeing 301 responses for paths, it will eventually delist the page.  You can speed up the process by also disallowing the paths in your robots.txt and/or submitting page/directory removal requests.  Just remember to backup your robot.txt (or better yet put it in your VCS) because it will get nuked during core updates.


keywords and description for front-page of drupal 7 site I managed to set page titles with the "Page Titles" module and keywords and description with the "Meta Tags (Quick)" plugin, however it seems like there is currently no way of having custom keywords/description for the front-page. Does anybody knows of a work around this?

Try the Meta tags module

It'll allow you to set keywords and descriptions to your site, and you can override those settings to be different for the front page.


Commands character limit? I have 2 functions in a custom AJAX callback which are really confusing me, one returns an image from a single node, the other retrieves a list of nodes first, then loops through them and returns images from each of them, even though the code which returns the image HTML is shared by both functions, the multiple node return wraps everything in a div.

Single AJAX callback

function _append_thumb_to_deck($node) {
    if (!empty($node)) {
        if ($node->field_image) {
            // Load the image as a thumbnail
            $thumbnails = get_thumbnails($node);

            // Prepare an ajax command to insert the node html into our ajax wrapper.
            $commands = array();
            $commands[] = ajax_command_append('#thumbs', $thumbnails);
            $commands['effect'] = 'fade';

            // Render the commands into JSON and print them.
            print ajax_render($commands);
            exit;
        }
    }
}

Multiple AJAX

function _append_multi_thumb_to_deck($node) {
    if (!empty($node)) {
        if ($thumbs = get_thumb_list($node->nid)) {
            // get_thumb_list is just a function to return an array of Node ID => Node object
            // Load each image as a thumbnail
            foreach ($thumbs as $nid => $node) {
                if ($node->field_image) {
                    $thumbnails .= get_thumbnails($node);
                }
            }

            // Prepare an ajax command to insert the node html into our ajax wrapper.
            $commands = array();
            $commands[] = ajax_command_append('#thumbs', $thumbnails);
            $commands['effect'] = 'fade';

            // Render the commands into JSON and print them.
            print ajax_render($commands);
            exit;
        }
    }
}

HTML callback

function get_thumbnails($node) {
    $img = image_get_info($node->field_image[LANGUAGE_NONE][0]['uri']);
    $vars = array(
        'style_name' => 'thumbnail',
        'path' => $node->field_image[LANGUAGE_NONE][0]['uri'],
        'width' => $img['width'],
        'height' => $img['height'],
        'alt' => t(''),
        'title' => t(''),
        'attributes' => array(
           'data-nid' => $node->nid,
        ),
    );
    $thumbnail = theme_image_style($vars);
    $thumbnail = "
nid}'>{$thumbnail}
";
    return $thumbnail;
}

This returns something like

I can even inspect the HTML which is intended to be returned by the multiple function and it appears to be correct, it's just a long string of multiple li tags containing images, properly formed HTML, no hanging tags, no opening or closing divs etc, and yet for some reason, the function to append multiple thumbs wraps everything in a div, whereas the other one doesn't.

Is there some kind of character limit or something which is causing it to be added in a div?

Apparently yes, because reasons

https://stackoverflow.com/questions/9607393/drupal-7-ajax-command-creates-unwanted-div

The solution to anyone else having this issue is to use either your own callback, or instead use ajax_command_invoke("#my-div", 'append', array($content)); and that will do the same as ajax_command_append, both solutions are more fleshed out in the link


custom module to create multiple forms with pop-ups I am working on a custom module to create a form. Functionality of the module is as follows: The first form has an url, on clicking the url it should show another form as a pop-up.
How can i call these forms in the hook menu.
Does tools_js has any significance?

<?php

function patient_menu() {

$items['patient_add/mainpage'] = array(
    'title' => 'New Patient',
    'page callback' => 'patient_form',
    'page arguments' => array(),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_CALLBACK,
);
//a link to add patient diseases

$items['patient_add/%ctools_js'] = array(
'page callback' => 'patient_callback',
'page arguments' => array(1),
'access callback' => 'user_is_logged_in',
'type' => MENU_CALLBACK,
);

return $items;
}

 // a function to make a  link
function _patient_make_link($link_text = '') {

 return '
' . l($link_text, 'patient_add/nojs', array('attributes' => array('class' => 'ctools-use-modal'))) . '
';
}
//first form

function patient_form($form, &$form_state)  {
ctools_include('modal');
ctools_modal_add_js();

$form['p_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#size' => 30,
    '#maxlength' => 128,
    '#required' => TRUE,
);

$form['age'] = array(
    '#type' => 'textfield',
    '#title' => t('Age'),
    '#size' => 30,
    '#maxlength' => 30,
    '#required' => TRUE,
    '#attributes' => array('placeholder' => t( 'in Years' )),
);

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

_patient_make_link('add disease details');

return $form;

}

//Ajax menu callback

function patient_callback($ajax) {
if ($ajax) {
ctools_include('ajax');
ctools_include('modal');

$form_state = array(
  'ajax' => TRUE,
  'title' => t('disease details'),
);
$output = ctools_modal_form_wrapper('disease_form', $form_state);
if (!empty($form_state['ajax_commands'])) {
  $output = $form_state['ajax_commands'];
}
print ajax_render($output);
drupal_exit();
}
 else {
  return drupal_get_form('disease_form');
  }
}
//second form
function disease_form($form, $form_state){
  $form['disease_ids'] = array(
    '#type' => 'select',
    '#title' => t('Disease IDs'),
    '#multiple' => TRUE,
    '#options' => array(
        'Cancer' => 'Cancer',
        'Dengu' => 'Dengu',
        'Viral Fever' => 'Viral Fever',
        'Malaria' => 'Malaria',
    ),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;

}

function patient_form_submit($form, &$form_state) {}

You are partial on the right path, I would suggest following a guide like https://www.deeson.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7 and then work your way towards what you need based on that.


How to display an image in a report created with the Forena module? I created a report using the Forena module. In this report I want to display image which is saved in a private folder. I am fetching the image url from the file_managed table using file_load() method on the basis of file id.

How can I display the image in my report?

1. Display an image with a hardcoded path

The body of a Forena report is an XHTML file, which you can edit using the WYSIWYG report editor (ie the layout tab). So if you just add an image tag with a path pointing to your image, you can display such image anywhere in your report.

2. Transform the hardcoded image path into a Skin configuration option

Using Report Skins, you can use the technique of Defining skin configuration options. This allows for defining arbitrary variables that can be referenced in reports using the skin data context.

For example, assume you define a variable in the skin like so:

imagepath = path/to/image

Anywhere in your report, you can then refer to the token {skin.imagepath}.

3. Create a separate data block

If it makes sense for this specific question, you might want to consider just creating a separate (additional) data block related to the image to be displayed. That way you just retrieve the relevant data (row) from your file_managed table (as in your question), and surround it with whatever HTML markup you'd want.

4. Available FORENA hooks for adding reporting extensions

Yet another option might be to use some of the available Forena hooks. Here are some of them that may help you:

hook_forena_data_alter
hook_forena_parameters_alter

Disclosure: I'm a Forena co-maintainer


How to add the twig debug extension in /var/aegir/platforms/drupal8-dev/sites/my_site_uri/settings.php

  # Additional site configuration settings.
  if (is_readable('/var/aegir/platforms/drupal8-dev/sites/my_site_uri/local.settings.php')) {
    include_once('/var/aegir/platforms/drupal8-dev/sites/my_site_uri/local.settings.php');
  }

in /var/aegir/platforms/drupal8-dev/sites/my_site_uri/local.settings.php

       <?php # local settings.php

$settings['container_yamls'][] =DRUPAL_ROOT . '/sites/default/services.yml';

in /var/aegir/platforms/drupal8-dev/sites/default/services.yml

 parameters:
   twig.config:
     debug: true
     auto_reload: null
     cache: false

The firebug console comments are working meaning twig debug is activated but dump (twig debug extension ) is not working .  why?
is there anything more to set in services.yml ?

  {{ dump() }}

Turn on Twig debugging by:

Copy sites/example.settings.local.php and rename to sites/default/settings.local.php

Go to sites/default/settings.php and uncomment the code below the comment relating to "Local development override configuration" and save the file.

if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

Open sites/development.services.yml in a text editor and add the following to the bottom of the file and then save the file

  parameters:
    twig.config:
      debug: true
      auto_reload: true
      cache: false

Note: use two spaces for each indent. Twig can be fussy with this.

The debugging will be visible as html comments in the source code. Use Chrome or other developer tools to inspect.

If you want to inspect the data structure of variables in a speciifc template, install Devel module and enable Devel and Devel Kint and then add this in your template:

# to dump everything
{{ kint() }}

# to dump a variable
{{ kint(page) }}

# to dump lower down in the data structure
{{ kint(page.content) }}


Get the body of content referenced in an Entity Reference field in node I have a content type "event" which contains an entity reference to another content type "speaker". The speaker content type contains image and body fields. If I select a speaker for my event, I am only able to output a link to the speaker within the event node page. Is there a way I can output the image and body fields within the referenced speaker content in the event node page?

Found it:

Content Type > Manage Display

Change Format to "Rendered Entity"


How to create review site with Drupal 7.7, FiveStar 2.x-dev, Node Reference URL, and Unique field? How to create review site with Drupal 7.7, FiveStar 2.x-dev, Node Reference URL, and Unique field?

Configuration:

Drupal 7.7
FiveStar 2.x-dev
Node Reference URL Widget
Unique field
Bartik theme

What I have now are:

Product node
User can write a review and rate each product node with multiaxis fivestar (value, price, and reliability).
User can create only one review per product (unique field module).
Rating is available when User create a Review node (Node Reference URL).

Questions:

How to embedded product node on the top of the review node? I want user to see what they are voting for without going back to the product node page.
How to create average rate of each category (value, price, and reliability) using Views?
How to compute average of all rating categories values? It means to create one number computed from average rating of value, price, and reliability.

Thanks for helping.

I think this is what you need, its simple and clear about the topic http://drupal.org/node/1308114 only the thing you need is to just spend couple of minutes on it, you'll surely get what you are trying to achieve.

Good luck!


drupal 7 entity and simple test What I can't workout is what steps I need to see if the entity is loaded using simple test. Any direction will be greatly appreciated thanks.

/**
 * @file
 * Definition of creation of a entity.
 */

/**
 * Coded entity display test.
 */
class CreateCoded extends DrupalWebTestCase {

  /**
   * Implements getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => 'Coded',
      'description' => 'Adding table to entities to create entity',
      'group' => 'Coded',
    );
  }

  /**
   * Enables modules that are need for test.
   */
  public function setUp() {
    // Enable any module that you will need in your tests.
    parent::setUp('coded');
  }

  /**
   * Tests for table coded.
   *
   * @Description
   *   Method needs to start with test if you wnat to test.
   */
  public function testCreateCodedEntity() {
    // how to I test the entity

  }
}

Try the examples module:

  This project aims to provide high-quality, well-documented API
  examples for a broad range of Drupal core functionality.

  The Examples project contains many modules which hopefully illustrate
  best practices for implementing various Drupal APIs. These modules can
  be enabled individually, and will typically add menu items to your
  site, which should guide you through their features. You can then look
  through the code to see what they are doing.

It has a drupal 7 & 8 entity example in which has a test as well.


Found index.php in files folder and all its subfolders? Anyone know what type of exploit is this? I'm cleaning up my drupal installations and i found in the files folder there was an index.php file and all its subfolders.
screenshot:

I still dont know what kind of exploit was done to get all these files in here. Anyone had something similar or know what this is?

Just an additional note, this looks like it could have been caused by the FCKEditor / CKEditor arbitrary file upload bug.

If using one of those WYSIWYGs, check this advisory:

http://drupal.org/node/1482528

and upgrade to latest


How to create test_endpoint? I am new to drupal and I am  using  services module for using REST   and  RESTWS module. I used RESTWS and could get the content of the node by  http://base_url/node/1.xml and now I need to add a node and users from my external PHP application in to  drupal. I googled and I found here that we need to use http://base_drupal_url/drupal7/test_endpoint/users . I tried to create a service from Drupal 7, but I dont know what should I give on endpoint title ,name and endpoint path and I assume I need to give the same endpoint path in the curl.

Any help as to how to check if rest server is installed and how to create endpoint path would be of great help.

I am using Drupal 7 with services  module services-7.x-3.0-rc3

Services module is easy to use, but it can be tricky to configure especially if you are new to the concept. So,  I am going to post the screenshots to make configuration of Services modules easy for "Drupal Answers" users.

Following is the version of Services module installed on my machine:

Create an endpoint called 'rest' as shown below:

Select the type of server and endpoint path:

Select the list of resources that you want to enable and specify aliases:

Select the response formatters and request parsers that you want to enable:

You can test your configuration as shown below:

You can get the list of all nodes as below:

And specific node as:

Following are the excellent examples scripts provided by MichaelCole here http://drupal.org/node/910598#comment-4677738 to create nodes from any external PHP application.

I am duplicating his code for completeness of this answer.

//--------------login to the server------------------------
$service_url = 'http://example.dev/rest/user/login.xml'; // .xml asks for xml data in response
$post_data = array(
    'username' => 'test',
    'password' => 'test',
);
$post_data = http_build_query($post_data, '', '&'); // Format post data as application/x-www-form-urlencoded
// set up the request
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // have curl_exec return a string

curl_setopt($curl, CURLOPT_POST, true);             // do a POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // POST this data
// make the request
curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line
$response = curl_exec($curl);
curl_close($curl);
print "LOGIN RESPONSE:\n";
var_dump($response);

// parse the response
$xml = new SimpleXMLElement($response);
$session_cookie = $xml->session_name . '=' . $xml->sessid;
// print "SESSION_COOKIE: $session_cookie";

file_put_contents('session_cookie.txt', $session_cookie);

//----------------create a node -------------------------------

$node_data = array(
    'type' => 'ct_metadata_core',
    'title' => 'test layer',
    'field_core_lat_n[und][0]' => array('value' => '90'),
    'field_core_lat_s[und][0]' => array('value' => '-90'),
    'field_core_long_e[und][0]' => array('value' => '180'),
    'field_core_long_w[und][0]' => array('value' => '-180'),
    'field_core_description[und][0]' => array('value' => 'National Data Buoy Center'),
    'field_core_originator[und][0]' => array('value' => 'NDBC'),
    'field_core_url[und][0]' => array('url' => 'http://www.ndbc.noaa.gov/kml/marineobs_as_kml.php?sort=pgm'),
    'field_cont_res_name_org[und][0]' => array('value' => 'test'),

);

$service_url = 'http://example.dev/rest/node'; // .xml asks for xml data in response
$session_cookie = file_get_contents('session_cookie.txt');

$node_data = http_build_query($node_data, '', '&'); // Format post data as application/x-www-form-urlencoded
// set up the request
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // have curl_exec return a string

curl_setopt($curl, CURLOPT_COOKIE, "$session_cookie"); // use the previously saved session

curl_setopt($curl, CURLOPT_POST, true);             // do a POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $node_data); // POST this data
// make the request
curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line
$response = curl_exec($curl);
curl_close($curl);
print "CREATE NODE RESPONSE:\n";
var_dump($response);

//----------------logout from the server-------------------------

$service_url = 'http://example.dev/rest/user/logout';
$session_cookie = file_get_contents('session_cookie.txt');

// set up the request
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // have curl_exec return a string

curl_setopt($curl, CURLOPT_COOKIE, "$session_cookie"); // use the previously saved session
curl_setopt($curl, CURLOPT_POST, true);             // do a POST
curl_setopt($curl, CURLOPT_POSTFIELDS, ""); // POST this data
// make the request
curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line
$response = curl_exec($curl);
curl_close($curl);
print "LOGOUT RESPONSE:\n";
var_dump($response);


How to place a menu link in views footer? I have created a page that displays the latest news. On the right side of the page using context module i have placed a "Recent news" block (Created using views). The recent news block shows 4 recently created news. I have added a "link" field in each item to show "Read more" on the block.

I have created another page using views which displays the complete news created so far. I call this as news archive. My problem is i have to create a "To news archive" menu in the "Recent block" last line.

You have created a view for recent news. Just add a footer to the view and then implement php l() function for your menu in the global text area of the footer.


Ignoring accents/diacritics in apachesolr I have a site that's in English, but there's a fair amount of French text on it. So, there are some special characters like è, é, á, etc.

I don't want to worry about those diacritics at all when searching (using solr 4), so that, say "any e gives you every e"

Right now, I have it so if you search for non-diacritics, you get all the related diacritics (search for "siecle", and get "siècle"), but if you search using diacritics it won't find anything (search for "siècle" returns nothing.)

I've been up and down between playing around with mapping-ISOLatin1Accent.txt and using:

<charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>

and

<filter class="solr.ASCIIFoldingFilterFactory" preserveOriginal="false"/>

But nothing I've tried seems to have any change to this. I assume I have to add this to both  AND  in schema.xml, but I'm not sure which fieldtypes to do that in. There are fieldtypes of:

text_ws

"text field that only splits on whitespace for exact matching of words"

text

"A text field that uses WordDelimiterFilter to enable splitting and matching of words..."

text_und

"An unstemmed text field - good if one does not know the language of the field"

I've tried every combination I can think of, and cleared/rebuilt the index each time, but nothing. A search including diacritics always fails.

After looking through the admin site for Apache, it looks like the ASCIIFoldingFiltorFactory is being added to the index analyzer, but NOT the query analyzer for the fieldtypes of text, but I don't know why; I added it the same way to both analyzers.

So, I think it was a mixture of problems/issues that arose, but they were more broad/were somewhat indirectly related to the symptoms. I'll mention the steps to fix it/figure it out:

On the web amin interface, I selected the core from the dropdown, then "Schema Browser" below it.
From there, I could tell which ACTUAL filters/tokenizers were getting loaded. The ASCIIFoldingFilterFactory was listed on the index analyzer for the text fieldtype, but not the query analyzer.
When I attempted to reload the core, it got an error, and failed. It said something about one of the diacritics already being loaded (it was talking about the mapping-ASCIILatinwhatever.txt file that I'd tried earlier)
I cleared that file, since I was trying to use a different filter, and the core was able to reload, reindex, and everything's working great now (and the filter is on the query analyzer.)

So, anyone else dealing with this issue, in suhort: Check your "Schema Browser" in the web gui for Solr on the core you're having trouble with!


Creating custom settings/variables for site I created a custom Form from a module in Drupal 8. Here is the code:

class SocialSettingsForm extends FormBase {

    public function buildForm(array $form, FormStateInterface $form_state){
        $form['facebook'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Facebook Username'),
            '#description' => $this->t('Enter your facebook username.'),
            'required' => FALSE,
        ];

        $form['actions']= [
            '#type' => 'actions',
        ];

        $form['actions']['submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Submit'),
        ];

        return $form;
    }

        public function getFormId(){
            return 'social_socialsettingsform';
        }

         public function validateForm(array &$form, FormStateInterface $form_state){
            $facebook = $form_state->getValue('facebook');
            if (strlen($facebook) < 5){
                // Set an error for the form element with a key of "title".
                $form_state->setErrorByName('facebook', $this->t('The username must be at least 5 characters long.'));
            }
         }

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

            $title =$form_state->getValue('facebook');
            drupal_set_message(t('You specified a title of %title', ['%title' => $title]));
         }

    }

The form works fine. But I'm not sure which direction and conventions to follow in order to make use of the user's input.

I would like to make use of the username the user enters, but I'm not sure how to store that input from the form. Ideally I would use these settings in a Twig template or a module.

UPDATE:
I have figured out how to add custom variables to my theme but I'm not sure how to get my form to access them. I was able to add

function mytheme_preprocess_page(&$vars){
    $vars['facebook'] = 'default';
}

But I'm not sure how to get my form to alter this variable.

To save custom configuration you probably want to use ConfigFormBase, the code would look something like this.

class SocialSettingsForm extends ConfigFormBase {
  ...

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'social.settings', // The name of the config you want to edit
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->config('social.settings')
      ->set('facebook', $form_state->getValue('facebook'));
  }
}

Then everywhere, you can use the config factory of the Drupal global object to get the config like this.

function some_preprocess_function(&$variables) {
  $facebook = \Drupal::config('social.settings')->get('facebook', 'default_value_if_no_value_is_set');
}

Note the above approach is centered around how you would do it in a module, saving and getting configuration. You should also note that it's best practice to define the configuration a module provides in a yml file located in module_folder/config/schema/module_name.schema.yml. I'm not 100% sure what the file is actually used for, as it's possible to save configuration not defined in the config file and all other features seem to "work" just fine without it.


Printing a content pane with Printer, Email and PDF versions Module I'm trying to determine how to add a content pane with an argument to a custom tpl.php file that is adding some other things to the print version.  I've done this before with a block, adding in the region that I needed to print out with the block, but in this case I don't think I can just print out "content_bottom" etc.

Example code taken from Programmatically display panels page

$node = node_load(array('type' => 'panel', 'title' =>'Your Node Page Title'));
$panel_node=node_view($node, FALSE, TRUE, FALSE);
print($panel_node);


Creating a very specific custom Views argument handler I've been employed to help fix and finish a D6 site. It's already late so any answers like "you need to change the underlying DB structure" - well, we can't we're stuck with it. (It was built by idiots and we're doing the best we can.)

This is for an educational establishment with a curriculum that has changed in the past (we're migrating from an older system and all the data has to come over) and will change in the future. Each version of the curriculum has a version number. Every student is on one of those versions depending on when they started, so they are all active.

There's a taxonomy term for each of the three versions (D6 remember) which is attached to each Course Module. Each user has a User Profile node which has the user's version.

I am trying to create a Views 3 argument handler which takes a user's UID and delivers the NIDs of all the Course Modules tagged with it.

UID -> User Profile node -> TID -> Course Module NIDs

The complexity comes for example where the TID must be from the Version taxonomy (user profile's have other tags).

Now I accept I may be overthinking this, maybe it can be done with relationships, but I feel using this would be so much easier to understand for any future developers because the views concerned are complicated and already have lots of relationships in them.

A solution would be great (I know, presumptuous) but I have contributed quite a bit to the community including modules and bug-fixes (lots on Search API last year). I have produced Views handlers before but it's never easy, and I have read most if not all the various websites and documentation.

Any help would be much appreciated.

Well this is what I ended up with, it's not entirely pretty - and I've never really grasped how the Views structure works, but it works.

/**
 * Implementation of hook_views_data().
 */
function msc_cc_vc_views_data() {
  return array('msc_cc_vc' => array(
    'table' => array(
      'group' => t('MSC Version Control'),
      'base' => array(
        'title' => t('MSC Version Control'),
      ),
      'join' => array(
        'node' => array(
          // links directly to node via vid
          'table' => 'node',
          'left_table' => 'node',
          'left_field' => 'vid',
          'field' => 'vid',
        ),
      ),
    ),
    'users_version_tid' => array(
      'title' => t('User\'s Version Term ID'),
      'help' => t('The taxonomy term ID (from the Version vocabulary) of the supplied user UID.'),
      'argument' => array(
        'field' => 'uid',
        'handler' => 'msc_cc_vc_views_handler_argument_users_version',
        'numeric' => TRUE,
      ),
    ),
  ));
}

/**
 * Implementation of hook_views_handlers().
 */
function msc_cc_vc_views_handlers() {
  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'msc_cc_vc') . '/views',
    ),
    'handlers' => array(
      // argument handlers
      'msc_cc_vc_views_handler_argument_users_version' => array(
        'parent' => 'views_handler_argument_many_to_one',
      ),
      // field handlers
      // filter handlers
      // relationship handlers
      // sort handlers
    ),
  );
}

And then the handler itself. Here I have hard-coded the Taxonomy VID because for this application it doesn't matter. You could steal the code for selecting vocabularies from other handlers, you might also want to allow multiple TIDs.

class msc_cc_vc_views_handler_argument_users_version extends views_handler_argument_many_to_one {

  /**
   * Called to implement a relationship in a query.
   */
  function query() {
    $this->ensure_my_table();

    // This is the supplied UID
    $uid = $this->value[0];

    // Not great Drupal but let's do some easy processing:
    $profile = content_profile_load('profile', $uid);
    $terms = taxonomy_node_get_terms_by_vocabulary($profile, 8);
    $version  = reset($terms);
    if (empty($version)) {
      drupal_set_message(t('The selected user does not have curriculum version.'), 'warning');
      return;
    }

    $def = $this->definition;

    // Rebuild the definition to create a unique relationship
    // that forces all results to have the selected version TID.

    $def['table'] = 'term_data';
    $def['type'] = 'INNER';
    $def['left_table'] = $this->table_alias;
    $def['left_field'] = 'vid';
    $def['field'] = 'revision';

    $def['table formula'] = "(SELECT td.*, tn.vid AS revision FROM {term_data} td INNER JOIN {term_node} tn ON tn.tid = td.tid WHERE td.tid={$version->tid})";

    $join = new views_join();

    $join->definition = $def;
    $join->construct();
    $join->adjusted = TRUE;

    // use a short alias for this:
    $alias = $def['table'] . '_' . $this->table;

    $this->alias = $this->query->add_relationship($alias, $join, 'term_data', $this->relationship);
  }
}

Enjoy.


Consolidating site CSS sheets As I'm moving on to the markup/stylesheet work on my site, I noticed that there are quite a bunch of CSS references to modules. Not only does it clutter the page markup, but it also refers to core Drupal modules, such as /modules/field/theme/field.css.

Since I have to override some of the style definitions (clear problematic floats, narrow a context, and some such), at the same time a question raises in my head - how do you guys approach those stylesheets: do you paste all the definitions in your theme css and remove unneeded css stylesheet links - or rather: - leave the stuff in place and override all problematic style definitions in your theme css?

How do you approach module-related stylesheets, such as Display Suite layouts?

I would like to avoid redundancy where possible, but only when the effort is justifiable.
Any insights?

Drupal will aggregate all of your style sheets into one when you enable it at admin/config/development/performance (Don't set it during development).

If you feel there is too many redundant stylesheets, you can use a module like Omega Tools which allows you to completely disable stylesheets provided by modules (even core).


Is "access administration pages" a valid access argument? In Drupal 7, it appears that access administration pages is a VALID access argument. Is this the case?
How can I determine all the correct access arguments?

That permission is defined from system_permission().

The access arguments that an access callback uses can be any value, as any access callback can define its own access arguments in the implementation of hook_menu().
If you are referring to the access arguments accepted from user_access(), which is normally the access callback used from most of the menus defined from Drupal modules, then the access arguments are just the string for the permission the user needs to have to access that menu. The "access administration pages" string is just a possible value, and third-party modules can extend the permissions adding new ones to the ones already defined from Drupal core modules.

To get all the permissions defined from the installed modules, and assigned to one of the roles used in your site, you can use the following snippet (it requires the Devel module):

$cache = array();
$result = db_query("SELECT rid, permission FROM {role_permission}");

foreach ($result as $row) {
  $cache[] = $row->permission;
}

dsm(array_unique($cache));

To get any permission defined from the modules enabled in your site, you can use the following snippet:

$permissions = module_invoke_all('permission');
dsm($permissions);

The difference between the snippets is that the first one can return also the permissions defined from a module that you disabled, as long as the permission has been assigned to a role; the second only returns the permissions defined from currently enabled modules. If you have temporary disabled a module, the second snippet will not return its permissions.


Fatal error on Drush run I've installed Drush following http://www.zyxware.com/articles/4497/drupal-installing-latest-version-of-drush-on-linux-system-and-troubleshooting.

Now, when I try to run Drush, I get this error message.

  PHP Fatal error: Class Symfony\Component\Console\Style\SymfonyStyle contains 4 abstract methods and must therefore be declared abstract or implement the remaining methods (Symfony\Component\Console\Output\OutputInterface::isQuiet, Symfony\Component\Console\Output\OutputInterface::isVerbose, Symfony\Component\Console\Output\OutputInterface::isVeryVerbose, ...) in /var/www/html/tubimer/vendor/symfony/console/Style/SymfonyStyle.php on line 33
  Drush command terminated abnormally due to an unrecoverable error.
  Error: Class Symfony\Component\Console\Style\SymfonyStyle contains 4 abstract methods and must therefore be declared abstract or implement the remaining methods (Symfony\Component\Console\Output\OutputInterface::isQuiet, Symfony\Component\Console\Output\OutputInterface::isVerbose, Symfony\Component\Console\Output\OutputInterface::isVeryVerbose, ...) in /var/www/html/tubimer/vendor/symfony/console/Style/SymfonyStyle.php, line 33

How do I fix these errors?

I suggest you to run -

composer self-update
composer update

It might solve your problem, but if it doesn't then try to install latest version of drush. I installed drush using https://www.drupal.org/node/1248790.
However, there is a full documentation on how to install drush for specific operating system. Link to documentation - https://www.drupal.org/node/1791676


Removing breadcrumb from the Homepage in Bartik theme (Drupal 7) I am trying to remove the breadcrumb from the homepage (Home link). I am using a bartik theme. I have a page--front.tpl.php and have tried removing the following code snippets and clearing the cache, but the Home breadcrumb is still there. Any help would be greatly appreciated

<?php if ($logo): ?>
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
    <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

<?php endif; ?>

and

<?php if ($breadcrumb): ?>

<?php print $breadcrumb; ?>

<?php endif; ?>

Edit: I just realised that my front page isn't actually picking up the page--front.tpl template. Why might this be??? :(

You can also comment them out on the page.tpl.php like so

<?php /* if ($breadcrumb): ?>

<?php print $breadcrumb; ?>

   <?php endif; */?>

And then if you want them back later... take the /* s out. :)


Is there any procedure to exclude taxonomy vocabulary terms from views display I am using drupal7. I created a view with nodes under category(Taxonomy) Vehicle.

It looks fine, I am able to output a good looking page with set of images, title,desc etc along with tags(I mean vocabulary == Vehicle).. Can any one guide me how to exclude taxonomy name from displaying in view.

Please help..

Thank you.


Creating a duplicate button for multiple entry field collection field I'm building a form for inputting people's travel plans, and as part of that, I need to capture who will be in what country on what days (see diagram for relevant section of the form)

Next to the Add Another Item button to allow me to add another top-level itinerary, I would like to add a 'duplicate last itinerary button' that would add another item to the itinerary list, but copy the contents of the last itinerary item into it.  Ideally, the button would only copy the data in the section surrounded by a dotted line on the diagram (the itinerary leg content) and leave the traveler(s) field blank.

If there is a ready module to do this, that would be fantastic, but I'd be perfectly happy for a code-based solution or failing that, pointers to good info.

I've found How to pre-populate multiple "field collection" fields in node form which in spite of being closed seems like it may contain good information on populating the entries.  I think I need to know how to do basically 3 things and what hooks make sense to accomplish them:

add a button alongside the other multi-entry field buttons
read the contents of the last itinerary leg field collection field in the list of itineraries.
add a new item, and populate the itinerary leg field collection fields with the values from step 2.

I think you should be using the Replicate API for this purpose. The module provides an API to duplicate entity along with many hooks. It's targeted towards developers however there are several modules build on top of it.

With respect to your use case, there is an implementation for supporting field collections. I think it will be the closest solution for you what you.


XAMPP and Acquia Dev Desktop I installed XAMPP on my local machine to use it for Drupal. But all the navigation between all the localhost websites are really slow, no matter if it's a brand new vanilla Drupal website or if it's a commerce website, drupal 7 and/or drupal 8.

I tried everything from apache config to mysql config to windows config.

I decided to try to either re-install XAMPP or install Acquia Dev Desktop instead.

2 questions:
 if i want to re-install XAMPP, do i need to uninstall it first or will it reinstall over it just fine?
 if i want to install Acquia DEV Desktop, do i need to un-install XAMPP first?

Thanks...

if i want to install Acquia DEV Desktop, do i need to un-install XAMPP first?

No, you can run them both at the same time by configuring different ports in Acquia Dev Desktop. Acquia Dev Desktop will also create its own hostname, so you'll access it differently. Eg, http://othersite:8080


Is there a way to run drush updb without going to maintenance mode I have a live site which runs on drupal 8. I am using drush 8.5.3 with the installation. Whenever I run drush updb the site automatically goes to maintenance mode. Is there a way to do this without going to maintenance mode. In simple words, can I use drush updb with my site running?

Actually, if you take a look at the drush code for updatedb command, you can find this piece of code in updateBatch() function:

$original_maint_mode = \Drupal::service('state')->get('system.maintenance_mode');
if (!$original_maint_mode) {
    \Drupal::service('state')->set('system.maintenance_mode', true);
    $operations[] = ['\Drush\Commands\core\UpdateDBCommands::restoreMaintMode', [false]];
}

For safety reasons, the drush command puts your site in maintenance mode during the update and then set it back online once it is completed. It prevents your users from accessing the website and generate possible conflicts within the database while it is updating.

There is a pretty clear explanation of this here

If you really wish to avoid the maintenance mode, though, you could run update.php directly from your website.


How to use EntityFieldQuery etc. to return a particular field efficiently? A taxonomy has a lot of big fields attached, but one of these fields is a short text field called external_identifier.

In code, I need to obtain an array mapping external_identifiers to tids for a given list of external identifiers.

So in raw SQL this is very efficient:

SELECT entity_id, field_external_identifier_value
  FROM field_data_field_external_identifier
 WHERE field_external_identifier_value IN ('a123','b567',...);

I understand I should be using EntityFieldQuery, but this only gives me an array of tids, keyed by ...tid. Then if I loop those and call entity_load it will be doing lots of separate lookups and loading a whole load of stuff I don't need. This looks really inefficient.

I understand that EntityFieldQuery will only return Ids, so is there a better way?

Or do I just resort to SQL?

The safest way to get a field value in Drupal is to load the whole entity using the API - Drupal is a modular system and this allows other modules to interact with the data. There are ways (see Clive's answer) to load the field with the API without having to load the full entity - but this is still much less efficient than a raw SQL query.

The question however is how often you need to run this inefficient code. Presumably you only need to run this code when entities have been modified - so while caching entities is not an option, you could well cache your map and only rebuild it when an entity has been modified (ie. on cache clear).

If your entities are modified very often, then rather then rebuild your map every time, you could use hook_entity_update and then edit that entitie's entry in your map - so continuously modify your map.

This approach may or may not be faster than using an SQL query every time you need your map - it depends on how often entities change and how often you generate the map.

That being said, it is extremely unlikely that Drupal 7's core database schema is going to change at this stage - you'd be quite safe using direct SQL queries (in particular if this is your own code as opposed to a module you want to release).


How to load Node and Paragraphs using target_revision_id? In Drupal 8, How to load Node and Paragraphs using target_revision_id?
For node I used \Drupal::entityTypeManager()->getStorage('node')->load($nodeId); . I tried this for revision id: \Drupal::entityTypeManager()->getStorage('node')->loadRevision($vid);

The second line probably should be:
\Drupal::entityTypeManager()->getStorage('paragraph')->loadRevision($target_revision_id)

It is recommended, though, to load the referenced entities through the field:
The first paragraph:
$paragraph = $node->{$field_name}->entity;

The second paragraph:
$paragraph = $node->{$field_name}->get(1)->entity;

All paragraphs:
$paragraphs = $node->{$field_name}->referencedEntities();


Confirmation message not getting rendered when printing the elements seprately in twig and ajax is enabled Iam using the following twig code in webform-submission-form--newsletter-signup.html.twig

                            {{ form.elements.url }}

                                {{ form.elements.email }}

                         {{ form.elements.actions }}

                    {{ form.form_build_id }}
      {{ form.form_token }}
      {{ form.form_id }}

and Iam using the following code in webform--newsletter-signup.html.twig

 <form{{ attributes.addClass('subscribe-form') }}>

  {{ title_prefix }}
  {{ children }}
  {{ title_suffix }}

</form>

When I try to use the default webform templates the message gets displayed after ajax request infact the message is returned as part of the data in response but when I use these templates the message is not present in ajax response what am I doing wrong here please help

You need to still include {{ title_prefix }} and  {{ title_suffix }} in your template

In the comments in the default webform.html.twig it gives a short description of the default variables "Additional output populated by modules" which includes essentially anything else apart from the form elements themselves


How to add another color to theme color pallette? I have custom theme which is using Color Pallette from Bartik. I want to add another color options:

 'fields' => array(
    'top-bar-' => t('Top Bar background'),
    'top' => t('Header top'),
    'bottom' => t('Header bottom'),
    'base' => t('Main background'),
    'sidebar' => t('Sidebar background'),
    'sidebarborders' => t('Sidebar borders'),
    'footer' => t('Footer background'),
    'titleslogan' => t('Title and slogan'),
    'text' => t('Text color'),
    'link' => t('Link color'),
  ),

top-bar- is id of top container (someone named it top-bar-, anyway it's best to remains the same)

In schemes array I added default color to every schema, e.g.:

    'top-bar-' => '#666666',

Now in colors.css I added:

#top-bar- {
    background-color: #666666;
}

I cleared cache but my new color pallette options doesn't appear in theme settings form :(
I read a few tutorials about this topic, but in my case it just don't work.

It's starts working when I changed color.module in line 234 (added TRUE param):

$palette = color_get_palette($theme, TRUE);

Caution: This removes any custom colour palette so you might want to note the colour settings somewhere

EDIT

Now I have removed TRUE param from code, my new field still appears and everything is working correctly.

Anyway at last problem is trivial to solve, just disable and enable theme again, but it remove blocks settings etc on this theme.