Views - get nodes flagged or created by me I want to list nodes flagged or created by me. You can think this as an "or" filter in views. is there a way to do in in views and flag ?

Views 3 supports groups of filters joined by OR.

Edit your View.
Under "Filter criteria" click the little down arrow next to "Add" and select "And/or, rearrange".
Create a new filter group with the filter(s) you want.
Change "operator" to "OR".
Save.

If you're using Drupal 6:

  Views Or allows Views to
  combine filters or arguments with OR and fields with COALESCE.


How can I bootstrap? How can I bootstrap Drupal 8 from an external script?

This an example script from the RabbitMQ Work Queues tutorial.

require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;

$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
$channel->queue_declare('task_queue', false, true, false, false);
echo " [*] Waiting for messages. To exit press CTRL+C\n";
$callback = function ($msg) {
  echo ' [x] Received ', $msg->body, "\n";
  sleep(substr_count($msg->body, '.'));
  echo " [x] Done\n";
  $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
};

$channel->basic_qos(null, 1, null);
$channel->basic_consume('task_queue', '', false, false, false, false, $callback);

while (count($channel->callbacks)) {
  $channel->wait();
}

$channel->close();
$connection->close();

Within a worker script like this, I need to be able to create nodes.

How can I bootstrap Drupal 8 in this script?

Php Access User Data from external script? and Bootstrap from external script bootstraps passing a fake request to the kernel, which to me looks like a work-around.

In Drupal 7 you could do something like this, apparently.

// Bootstrap Drupal.
include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

I ended up inheriting the kernel and will adjust it as needed be.

Something like:

namespace Drupal\Core;

use Drupal\Core\Site\Settings;

class DrupalCliKernel extends DrupalKernel {

  public function bootstrap() {
    static::bootEnvironment();
    $this->setSitePath('sites/default');
    Settings::initialize($this->root, 'sites/default', $this->classLoader);
    $this->boot();
  }

}

And then:

use Drupal\Core\DrupalCliKernel;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalCliKernel('prod', $autoloader);
$kernel->bootstrap();

// Drupal is bootstrapped now.

Not yet sure if I miss something important, but I am most likely not using this, but instead relying on using HTTP requests that the worker will use as Drupal is too coupled to the HTTP request. Just putting it out if someone come here to try to accomplish something similar and want a jump-start.


Can't figure out how to set a context with t() This is a follow-up to this question on setting contexts using t().

I am attempting to set a context using t().

I am trying to set the context for the translation of State to geo.  My code looks like this:

$format['locality_block']['administrative_area'] = array(
  '#title' => t('State', array('context' => 'geo')),
  '#size' => 10,
);

This doesn't give any errors but it also doesn't create the translation unit with the context, either.  Any clue what I'm doing wrong?  (It's probably something obvious; I'm not good with PHP.)

The second argument of the t() function are the replacements and not options.


Programmatically insert webform result I'm using drupal 6 with the webform module installed.

I need to be able to remotely POST, from PHP results to a webform. Pseudocode:

<?php
//File: remote_script_not_hosted_on_the_same_server_as_drupal.php

$results = array(
'name' => 'testname',
'age' => '6',
);

$node = 5;

$url_to_drupal = 'http://remote_server.com/drupal-6.2';

insert_into_webform($results, $node, $url_to_drupal);

Of course, this example isn't perfect, but you (hopefully) get the idea.

How would you go about doing this?

I've opened an issue on the drupal queue: http://drupal.org/node/1082016

I'm concerned about these two fields invalidating my remote submission:

------WebKitFormBoundaryKIiNRZCPZIFlYWKc
Content-Disposition: form-data; name="form_build_id"

form-58f36748bfffd6752f204eadf1ba87c9
------WebKitFormBoundaryKIiNRZCPZIFlYWKc
Content-Disposition: form-data; name="form_token"

e4becb726ea858b6914980b9142b7f30

Have you tried using PHP to manually send the POST data? Here is a snippet from http://www.webmasterworld.com/php/3164561.htm

$server= 'www.someserver.com';
$url = '/path/to/webform/posturl';
$content = 'name1=value1&name2=value2';
$content_length = strlen($content);
$headers= "POST $url HTTP/1.0\r\nContent-type: text/html\r\nHost: $server\r\nContent-length: $content_length\r\n\r\n";
$fp = fsockopen($server, $port, $errno, $errstr);
if (!$fp) {
    return false;
}
fputs($fp, $headers);
fputs($fp, $content);
$ret = "";
while (!feof($fp)) {
    $ret .= fgets($fp, 1024);
}
fclose($fp);
print $ret;

Of course this would fail if you are using any form of captcha on the form, and will also currently fail if you are required to be authenticated to post a reponse


What are some drawbacks/benefits of using ctools? What is the purpose of ctools?

Are there any drawbacks in using ctools for one's programming needs?
Also, what are some benefits to using ctools? From the project page it seems to just be a large collection of random tools.

Discovered the best place to learn this is actually from a lecture from drupalcamp austin in 2010 by Erik Summerfield.

http://vimeo.com/17957123

That's just a start. Otherwise going through example ctools integrated modules has helped as well. The fact is (at this moment) documented use case examples are limited.


How to hide a block for specific users using Views? I have a bunch of blocks that I would like to have hidden by default and only shown to specific users that will be determined by a view.

Is this possible? If so, how?

Under the block settings in views, there is an option called "access," which you can use to allow access based off of role (anonymous user, registered user, etc). If your users have specific user roles that you can filter off of, you can use this to do what your looking for.


Editing entity property (title) with ECK and editablefields I'm using Entity Construction Kit and Editablefields.  When configuring the "Manage Display" of a bundle, the properties (specifically, "title") do not have the option of "editable".

Is there a way to make the entity property fields editable as well?  I'm considering doing a dummy field that updates the entity title on save.

I think you can use Title module to replace the default title field.


How do I filter the user who have logged in once in a view? I need to create a view that shows the users who have logged in once to my site.
How can I implement this with Views?

Take a look at the User Stats module.  This will provide a count of how many times users log in and it integrates with Views 2


How can I rename uploaded files programatically? (auto-rename image files) I am aware that the File Paths module allows administrators to use tokens to set patterns for renaming files, but as of writing (Jan 2015) there are more than 100 bugs in the queue and no updates to the dev version in almost one year.  (I also installed it and it and was unable to get it working.) So, I want to do this programmatically.

My goal is to rename all new user-uploaded image files on my Drupal 7 site to this pattern: [uid of logged in user][timestamp].extension.

Being able to rename them with the UID is very important because these files are often downloaded and exchanged (sent back and forth via email, without reference to Drupal), and we need an easy way to identify which user originally uploaded the file after it has been downloaded from the site.

I am using the Transliteration module. For inspiration, I also took a look at the File Entity Paths module, but it didn't provide me any insight.  I further consulted this article on file-naming best practices from Acquia but it provides no suggestions for doing this programmatically.

Assuming you are talking about the core file functionality, you can modify the filename in hook_file_presave() and modify the filename property.

function mymodule_file_presave($file) {
  $parts = pathinfo($file->filename);
  $file->filename = $file->uid . $file->timestamp . '.' . $parts['extension'];
}

Drupal will handle changing any other properties that need to be changed.

Some issues to be aware of:

Upload forms will expose the new name to the user after he clicks 'Upload'. It may be confusing to upload a file with a regular filename and see it changed to a string of numbers.
There is a note on the hook_file_presave documentation that the hook "doesn't distinguish between files created as a result of a copy or those created by an upload." If you do need to distinguish, check out the $file->source property or try calling menu_get_object() to figure out if the user is on a page with an upload form or not.
Consider using a dash between the uid and the timestamp for your naming convention. Your timestamps will all start with 1 (until 2033 anyway), and users with UIDs ending in 1 (e.g 11, 21, etc.) will make the filename confusing to read.


Prioritize Row within View based on Taxonomy Term I am generating rows through a view and have specific requirement for listing on my page.

What I want is if there is one specific term value of my Filter Taxonomy, the row should show itself first.

For each result of this view, I have a term value of one taxonomy (Role).

Possible term values for this Taxonomy (Role) are:-

Leader
Manager
Editor
User

Now what I want is, that which ever row's Taxonomy value is Leader, the row should be shown first and then the Manager, then the Editor and at the end, of User.

Any help how I could achieve this in Views?

Thanks.

On your view, for Sort Criteria remove whatever you're current using (post date is usually the default) and add Taxonomy term: Weight

Then go to admin/structure/taxonomy go to list terms and click on show row weight link (far right) and give them different weight numbers, or use the four arrows icon to drag them and arrearage them in the order you want them to show in.


Disable a default theme I want to disable the default theme in my Drupal 7.5 system installation instance. How can I do this? I can't find a Disable link using the Creative Responsive theme version 7.x-1.1.

Drupal requires that one theme must always be set as default. Further, you cannot disable a theme that is currently set as default.

Best bet would be for you to enable another theme, set it as default, then disable the one you don't want.


Customizing a Drupal 7 block menu I installed the Menu block module, and it seems to work fine.

I need to change one of the menu HTML output; instead of the following HTML tags:

Home

Our Rides

I want to have:

Home|Our Rides

I tried implementing a hook, but it doesn't work.

function bsrentals_menu_item_link__menu_block($variables) {
      print 123;exit;
}

Well, what you want to achieve ... Eg, output a horizontal list of links with "pipes" between them can be done in Drupal with the HTML and CSS drupal provides you.

What you need to refer to is a book on CSS.

A random Google of this technique yields:
http://jamesowers.co.uk/css-tutorials/50/horizontal-css-list-menu/

In a nutshell, you want to set the list-item as relative and to display inline in CSS. Give them some spacing and for instance add a right-border to every list item with your color choice. Then if you really want using a CSS/Jquery selector of :last-child remove the trailing right border if it bothers you.

If you are intent on rewriting and bending the HTML and CSS to your will because the above approach elludes you .... you can do 1 of 2 options:

1) using the http://drupal.org/project/devel_themer you can find the specific block in question within your theme. You can then alter the necessary template file(s) in drupal to alter the HTML produced from Drupal to meet your criteria. Menus are shown in blocks on the page. So you could find the theme function for the menu in question and override its output in your theme. Devel_theme should be able to tell you the correct function to override if your's isn't working.

Or you could create a really silly function like below in your template.php file and call it as needed from your .tpl files. The below code relies on the http://api.drupal.org/api/drupal/includes--menu.inc/function/menu_tree_all_data/7 function to pull a menu's items by the menu-name. See the linked API page to find out how to find out what specific menu in drupal you want to load ... then we simply create the HTML from the menu links as in the function. I really really dont recommend you do this. Either learn CSS and Jquery to render the default content drupal provides you with to appear as you want, or learn how to change the template files gracefully ...

/*
What does menu_tree_all_data() return ... well let's see below:

$ drush eval 'print_r(menu_tree_all_data("main-menu"));'Array
(
[49950 Home 240] => Array
    (
        [link] => Array
            (
                [menu_name] => main-menu
                [mlid] => 240
                [plid] => 0
                [link_path] => <front>
                [router_path] =>
                [link_title] => Home
                [options] => Array
                    (
                        [attributes] => Array
                            (
                                [title] =>
                            )

                    )

                [module] => menu
                [hidden] => 0
                [external] => 1
                [has_children] => 0
                [expanded] => 0
                [weight] => -50
                [depth] => 1
                [customized] => 1
                [p1] => 240
                [p2] => 0
                [p3] => 0
                [p4] => 0
                [p5] => 0
                [p6] => 0
                [p7] => 0
                [p8] => 0
                [p9] => 0
                [updated] => 0
                [load_functions] =>
                [to_arg_functions] =>
                [access_callback] =>
                [access_arguments] =>
                [page_callback] =>
                [page_arguments] =>
                [delivery_callback] =>
                [tab_parent] =>
                [tab_root] =>
                [title] => Home
                [title_callback] =>
                [title_arguments] =>
                [theme_callback] =>
                [theme_arguments] =>
                [type] =>
                [description] =>
                [in_active_trail] =>
                [access] => 1
                [href] => <front>
                [localized_options] => Array
                    (
                        [attributes] => Array
                            (
                                [title] =>
                            )

                    )

            )

        [below] => Array
            (
            )

    )

[49951 Student Login 239] => Array
    (
        [link] => Array
            (
                [menu_name] => main-menu
                [mlid] => 239
                [plid] => 0
                [link_path] => student/login
                [router_path] => student/login
                [link_title] => Student Login
                [options] => Array
                    (
                        [attributes] => Array
                            (
                                [title] =>
                            )

                    )

                [module] => menu
                [hidden] => 0
                [external] => 0
                [has_children] => 0
                [expanded] => 0
                [weight] => -49
                [depth] => 1
                [customized] => 1
                [p1] => 239
                [p2] => 0
                [p3] => 0
                [p4] => 0
                [p5] => 0
                [p6] => 0
                [p7] => 0
                [p8] => 0
                [p9] => 0
                [updated] => 0
                [load_functions] =>
                [to_arg_functions] =>
                [access_callback] => 1
                [access_arguments] => a:0:{}
                [page_callback] => _dew_auth_login_page
                [page_arguments] => a:0:{}
                [delivery_callback] =>
                [tab_parent] =>
                [tab_root] => student/login
                [title] => Student Login
                [title_callback] => t
                [title_arguments] =>
                [theme_callback] =>
                [theme_arguments] => a:0:{}
                [type] => 6
                [description] =>
                [in_active_trail] =>
                [href] => student/login
                [access] => 1
                [localized_options] => Array
                    (
                        [attributes] => Array
                            (
                                [title] =>
                            )

                    )

            )

        [below] => Array
            (
            )

    )

)

*/

function i_dont_advise_this($menu_name) {
  $data = menu_tree_all_data($menu_name);
  $links = array();

  foreach($data as $MenuItem => $item) {
    $links []= l($item['link']['title'], $item['link']['link_path']);
  }
  return implode('|', $links);
}

print i_dont_advise_this('main-menu');
# yields =>
# Home|Student Login


User profile layout vs. contact form option On the user profile I have some 12 fields for the users to enter their contact information and other details about themselves. The option to activate/deactivate the personal contact form is somwhere between the fouth and the fith field.

I would like to have to personal contact form option to be on a position I intend it to be on – e.g. the first position, before all other fields, since it's an option – and not a field. Disabling the drag'n'drop i can actually rearrange the fields in the intended order. But when I switch drag'n'drop field sorting back on, the checkbox jumps back down somewhere between field four and five.

Any suggestions anybody?
Thanks!!

found the answer / an answer to my question: Installing and enabling the module profile2 helped. The missing fields ("Contact user element") showed up in the fields list and became sortable through drag'n'drop.


How to export pseudo fields display configuration to code How can I export the configuration of pseudo fields as set from the display configuration for my entities types and their bundles ? When exporting a normal fields instance (with Features) its display settings, for each available view mode, are exported with it. But I cannot find how to export the settings for the pseudo fields such as the History field of a User entity and the File field for a File entity.

Strongarm will do this because field_bundle_settings() stores the settings in a huge variable called field_bundle_settings. There is a patch to move it into several variables, but it'll be variables nonetheless.

Edit: I guess the core source code counts as "official source", doesn't it?


Rules condition to check if user is a member of a specific group type? I'm trying to create a rule where the condition is that the currently logged in user is a member of a specific type of group. Can anyone offer assistance on the proper data selectors to use to build this condition?

For example, we have three types of groups:

Group Type 1
Group Type 2
Group Type 3

The condition, upon login, should be to check if the logged in user is an active member of Group Type 2.

Thanks in advance.

The is a rule action "Rules has role" this should do it.


Commerce add to cart while checkout I would like to add some products to my cart while I am on checkout process. The cart appears to be empty at the time. I want to make a selection of some add-on products on the checkout process.

I created my own custom checkout pane(it's a form). Also a submit function.

There are "commerce_line_items" in the order object, but then I get an error that says my entity is missing bundle. There is also 'commerce_order_total' that includes the totals? so I can't just edit the object/array?

This is how I create my line item:

$line_item = commerce_product_line_item_new($product, 1, $order->order_id);

This is how I am trying to add it to my order:

$order->commerce_line_items['und'][] = array('line_item_id' => $line_item->line_item_id);

You likely need to save the line item before adding it to the order. The order total should be recomputed for you automatically on save.


Field is translatable, but field instance is not When exporting configuration for a node type with fields with Drupal 8.2, I noticed that translatable: true is set in field.storage.node.my_field.yml, but translatable: false is set in field.field.node.living_word_comment.my_field.yml. my_field is of type Text (plain), i.e. string in the YAML file.

What does it mean for a field to be translatable, while the instance is not? It doesn't make sense to me.

Disclaimer: I'm not sure whether phrases like "field" and "field instance" are still applicable in Drupal 8, or whether that is just 7-speak.

Every node field has one storage setting. Here the field is configured how it is stored in the database, field type, single or multi value, or translatable or not. This settings can't be changed after the field is set up and filled with data. It's shared among all content types.

The field can be used in multiple content types. In each content type it can be configured to be translatable. (Option "Users may translate this field"). This setting can be changed any time and without data loss.

If you want the field to be translatable, you need both options set, in the field storage and in the content type where the field is used.

If you use the UI, then you don't have to worry about this, because Drupal sets the storage settings the first time you place a field in a content type.


Is it possible to make manual teaser breaks work with "Filtered HTML"? This question is about Drupal 8.

Placing the following line inside a story node's body (I guess it also works for other content types) adds a manual teaser break:

<!--break-->

In Drupal 7, to make manual teaser breaks work with the "Filtered HTML" text format it was necessary to add <!--> to the text format's set of allowed HTML tags (for instance, see this "Drupal Answers" post).

In Drupal 8, however, this solution no longer works: Manual teaser breaks are silently ignored even if <!--> is present in the allowed HTML tags of "Filtered HTML". I have tried to add a couple of plausible seeming combinations to the "Filtered HTML" text format, such as <!--break--> or <!---->, and a couple of implausible combinations (<!--...--> and <!--.*-->), but nothing works.

I double-checked and manual teaser breaks work fine when I switch a story's text format to "Full HTML" text format.

How can I get manual teaser breaks to work again with "Filtered HTML" in Drupal 8? If this is not possible I will have to go through all nodes of my site after the D7 > D8 migration and switch them to "Full HTML".

This comes down to being a problem of DomDocument and its childNodes property that does not include DomComments. Specifically, Drupal\filter\Plugin\Filter\FilterHtml::getHtmlRestrictions() will not consider any comment-like tags that are added in the 'allowed HTML tags' list. This is due to these lines in that function's code:

$html = str_replace('>', ' />', $this->settings['allowed_html']);
// Protect any trailing * characters in attribute names, since DomDocument
// strips them as invalid.
$star_protector = '__zqh6vxfbk3cg__';
$html = str_replace('*', $star_protector, $html);
$body_child_nodes = Html::load($html)->getElementsByTagName('body')->item(0)->childNodes;

This loads the text of the 'allowed HTML tags' text as an HTML DomDocument and retrieves the list of the children. Only 'proper' HTML tags will be listed as part of the childNodes property and therefore, the Drupal 7 workaround will not work for Drupal 8.

In order to solve this, one could override the FilterHtml plugin in order to allow <!--break--> to remain in the text.

One attempt following this approach exists here:

https://www.drupal.org/project/drupal8breaks

which was in turn inspired by

https://medium.com/@djphenaproxima/how-to-bend-drupal-8-plugins-to-your-nefarious-will-94da0c31f095

Good luck!

P.S.: Also available on GitHub https://github.com/stefanospetrakis/drupal8breaks


Custom search results usign Search API + views I am currently using Search API for indexing my content . I use Views for displaying search results and Views exposed filter for search form. In the search results page I use facets to filter based on content type, created date etc. I need to upgrade the search feature and provide the following features. Please let me know the Modules or APIs that can help me achieve this.

1) Split the search results based on content type.
Ex: If there are any nodes of content type A, content type B in the search results, I need to display the top 2 nodes of the content type A , top 3 nodes of content type B and the rest of the results.
Formatting of the result display is based on the content type.

2)In the facets I would like to display custom group names instead of the actual content types. Ex: If there are multiple content types like 'Books', 'Articles', 'Magazines' etc I would like to display the link in Facets as a single entry 'Publications' and in the view filter based on the actual content types.

Is it possible to achieve the above 2 features using search API? I am open to changing the approach for displaying search results(alternative for Views and exposed filter if required).

Please suggest

1) Although I can't give you the exact answer, what you're looking for is probably View Attachments (https://www.youtube.com/watch?v=s9GC-trMH0o). That allows you to display part of the view in a different way.

2) No idea.


How to hide "Manage Fields" and "Manage Display" tabs I'm making a website with Drupal 7, and I was looking through the permissions for Taxonomies. I wanted to give the website maintainers a central place to manage the vocabularies and add terms, sort the terms etc. So I gave their role the "Administer vocabularies and terms" permission under Taxonomy. This however resulted in an unwanted complication, mainly it gave them access to create new fields and manage their display ("Manage Fields" and "Manage Display" tabs).

Is there a way to give them access to the Vocabulary and Term edit screen which can be accessed through "Structure > Taxonomy" but however disable the "Manage Fields" and "Manage Display" tabs on the vocabulary edit screen?

I'm quite familiar with the notion of overriding and hooks in Drupal 6, but I'm quite new to Drupal 7 (in fact this is my first D7 website, made about 5 or 6 D6 websites) so I don't mind some coding solutions to this if any. Just looking for an answer or a push in the right direction.

Since no one has answered yet, I wanted to add that I'm willing to look into alternatives to the central area to manage taxonomies (admin/structure/taxonomy). Maybe I could look into creating a page with Views to simulate the taxonomies admin page.

Is it feasible and has anyone done anything like this before?

I know this was answered a while back, but there's a solution that doesn't require any custom or special modules.

If you disable the core fields ui module, the Manage Fields and Manage Display tabs will not show.

If this is a production site, this should be fine to do as you'll have already configured the fields how you want them. If you ever need to make a change, just enable the module again briefly.


Warning: Cannot use a scalar value as an array in _block_get_renderable_array() on hook_block_info / hook_block_view I'm trying to create a module that creates a block to a specific region so I use this module on multiple sites instead of using the admin menu copy and pasting creating blocks with HTML code in it and putting it in the region that I want it to be.

Somehow the block doesn't even shows up in the blocks admin section. Maybe I'm overlooking something but I quite sure my code is correct for the hooks implemented below:

/**
 * Implements hook_block_info()
 */
function bannert_block_info() {
    $blocks['bannert'] = array(
        'info' => t('bannert'),
        'cache' => DRUPAL_CACHE_PER_PAGE,
        'region' => 'three_33_third',
        'status' => 1,
    );

    return $blocks;
}

/**
 * Implements hook_bock_view()
 */
function bannert_block_view(){
    $block['subject'] = t('');
    $block['content'] = _bannert_get_bannert();

    return $block;
}

/**
 * get banner
 */
function _bannert_get_bannert() {
    return include_once('banner.html');
}

The only thing I'm doubting about is the _bannert_get_bannert() function but that doesn't prevent the block from being created, now does it?

I'm getting this error now:

  Warning: Cannot use a scalar value as an array in
  _block_get_renderable_array() (line 346 of /Users/Jack/Sites/drupal-7/modules/block/block.module). Fatal error:
  Unsupported operand types in
  /Users/Jack/Sites/drupal-7/modules/block/block.module on line 352

I changed the _banner_get_bannert() code to the following one:

function _bannert_get_bannert() {
    return "
push me
";
}

The error is gone, and the block is created.


Where is the button that will translate all countries from Countries module in all my 10 languages? After installation of Countries module I rest only 15 countries that I've translated one by one with Google Translate and my hands.

It's a pity cause my site is viewing and using in other countries too. But I need the automatic translation of country list in 10 site languages.

There is one more question that does not have an answer: How to translate all the country names provided by the Countries module in one shot?

And google also shows this: https://www.drupal.org/node/2096581 But if I try to upload this translations it does not change anything cause by default language is russian.

One professional developer said that here I can get de database http://dev.maxmind.com/geoip/geoip2/geolite2/ and using https://www.drupal.org/project/smart_ip I can translate my list of countries. But I do not believe in my power.

Please let me know if I can have solution of: How to translate countries list in several languages?

For large tasks like this consider automating. and not just using "Drupal". Can you make a CSV file of your countries list? Then write a small Bash, PHP, Ruby or any script to ask Google for the translation(s) 1 by 1. Then given your new big CSV file of English + 10 other columns of languages. Loop through the file rows and do a database insert to Drupal to create the translations ...

From the final CSV of country terms translated I would then try to use the Feeds or Migrate module to import them to Drupal, if I didnt want to write much code.


Core files updated, but getting "No Pending Updates" message This is my first time developing for Drupal, and it came time to update the site. I followed all the instructions in the update.txt file by doing the following:

backed up files and databases
put site in maintenance mode
deleted old files and installed new ones
ran update.php

The problem I'm running into is that update.php is telling me that there are "No Pending Updates". However, when I take my site out of maintenance mode and flush my cache, I'm still getting messages that I need to install security updates. Is this just a problem with my alerts system, or is there something I'm missing in the update?

Thanks, in advance, for helping a Drupal Noob.

Hope this is helpful for other beginners:

Turns out, what I did wrong was not copy the new core files from the modules directory. I assumed that I wouldn't need to copy those (just like the "sites" folder), and I feared losing my installed modules. Turns out, as you probably already know, the core files in the modules folder needs to be updated as well.


Using behat to create nodes and testing user owns them I would like to create a Behat test that confirms a user can only see content they own or are referenced in.  The struggle is that I can't figure out how to assign the content to created user.

Starting with something like:

Given users:
| name | status |
| test | 1      |
Given "Page" content:
| title | uid |
| A title | ?? |

I need to create several nodes to test, and it seems...odd... that I would need to do the entire steps (e.g. Then I go to register, then I go to node/add/page, ....).

How do I know the uid of the user created in the Given?

In the example in features/api.feature you'll find how to do this:

  Scenario: Create nodes with specific authorship
    Given users:
    | name     | mail            | status |
    | Joe User | joe@example.com | 1      |
    And "article" nodes:
    | title          | author   | body             | promote |
    | Article by Joe | Joe User | PLACEHOLDER BODY | 1       |
    When I am logged in as a user with the "administrator" role
    And I am on the homepage
    And I follow "Article by Joe"
    Then I should see the link "Joe User"


Set image format of field_view_field image field I'm using a function to place an image from a user field into nodes that the user creates. The display is set to thumbnail in default, user account and tokens, but it shows up as original in the node. Is there a way I can set the format in the function I'm using somehow?

function MYTHEME_preprocess_node(&$vars) {
  $node = $vars['node'];
  $user = user_load($node->uid);

  $logo_var = field_view_field('user', $user, 'field_business_logo');
  $logo_print_var = drupal_render($logo_var[0]);
  $vars['logo_print_var'] = $logo_print_var;
}

Yes, you can set the field value display settings as a parameter to field_view_field

e.g:

// Customize field display settings.
$display_settings = array(
  'label' => 'hidden',
  'settings' => array(
    'field_multiple_limit' => '1',
    'field_multiple_limit_offset' => '0',
    'image_link' => 'content',
    'image_style' => 'thumbnail',
  ),
  'type' => 'image',
  'weight' => 0,
);
// Get field value
$logo_var = field_view_field('user', $user, 'field_business_logo', $display_settings);


How to make an upsert query with two keys? I have a custom table with a primary key made from two fields (route, uid) and I want to use the upsert() method to insert or edit a record. The problem is that the key() method only accept one key which will be used to identify the existing row. But I have two (route and uid)

  Sets the unique / primary key field to be used as condition for this
  query.

public function key($field) {
  $this->key = $field;

  return $this;
}

Maybe I'm missing something or I misunderstand the upsert() method. So, Can I make an upsert query with two keys?

Edit: I'm using mysql.

At this moment I don't know why but if I use only one key the query works as expected (using the two database keys as a key in the upsert, when I only says $query->key('route');):

$route = \Drupal::routeMatch()->getRouteName();
$uid = $this->currentUser->id();

$query = $this->connection->upsert('forcontu_database_counter')
          ->fields([
    'route' => $route,
    'uid' => $uid,
    'user_count' => 1,
    'lastcount' => time(),
  ]);
$query->key('route');
$query->execute();

If I change the uid (using a diferent user in the site) in the same route (page) Drupal insert a new record (don't make an update in the existing route) and I only use one key, in this case route.

EDIT:

This always will work because if you see the code inside the __toString() function the key property is never used:

public function __toString() {
    // Create a sanitized comment string to prepend to the query.
    $comments = $this->connection->makeComment($this->comments);

    // Default fields are always placed first for consistency.
    $insert_fields = array_merge($this->defaultFields, $this->insertFields);

    $query = $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES ';

    $values = $this->getInsertPlaceholderFragment($this->insertValues, $this->defaultFields);
    $query .= implode(', ', $values);

    // Updating the unique / primary key is not necessary.
    unset($insert_fields[$this->key]);

    $update = [];
    foreach ($insert_fields as $field) {
      $update[] = "$field = VALUES($field)";
    }

    $query .= ' ON DUPLICATE KEY UPDATE ' . implode(', ', $update);

    return $query;
  }

}

But always you need to set the key, if you don't set the key property you will get an exception:

protected function preExecute() {
  // Confirm that the user set the unique/primary key of the table.
  if (!$this->key) {
    throw new NoUniqueFieldException('There is no unique field specified.');
  }
...

Read more about this at: Why we need the key property in the Upsert class if it is never used?


How do I display real names instead of usernames for referenced users? Here are the steps which I followed:

Added the user referenced field in the content type so one author can add multiple users who contributed in that content.
Using views i am showing the content and showing the users who contributed in this node.

My issue is that the view is showing the usernames of all the users. I want to convert those usernames to the Display name.

As with most problems this one too can be solved in more than one way.

Probably the easiest, common, and "most Drupal" way is through using View modes.

View modes

View modes are different ways of displaying entity content, depending on the context. Don't confuse them with Views module that is used for building lists of entities, they are completely different things.

An example of a View mode: you want the user profile page to show all user user fields, but in a lot of other places on the site you need the username and their geo-location, so you keep the Default User View mode for profiles, and create a new View mode where you only enable the username and geofield. Then activate the new user view mode in all places where you need to show the user with their geo-info.

In your case you have a User Reference field in Content Views and you want to change how the user info from that field is presented:

Create a new User View mode under People Manage display (/admin/config/people/accounts/display) > Custom display settings
Enable the newly created View mode. After you enable it and Save the page will reaload and a new Drupal tab will appear named after your new View mode.
Visit the page of the newly created View mode (click on that tab) and adjust which user fields you want to show under that View. In your case that might be firstName and lastName, disable all others by dragging them down to the Disabled list (and Save).
Edit your Content Views (this is now the list of content you mention in your question, not the View modes), edit the User reference field and change the View mode option to the one you created in step 1.

Now your User reference field will show only the user fields you have enabled in the View mode on People account configuration.

You can use this View mode in other places too where you want any User data to display only as the Display names.

Through Views

Alternatively, you can achieve the same result with Contextual filters within a Views Block Display to show only users referenced by the article you're currently viewing, and only showing that Block on the pages of that specific Content Type.


Using Views to filter images based on taxonomy of page node I have many image files with taxonomy associated with them. I have page nodes using the same taxonomy vocabulary. I want to create a Views block that filters the images displayed based on what that page uses for that vocabulary.

Fake example:

I have a page that is tagged with carrots and broccoli.
I have image files tagged with the same terms. I want to place a Views block on the page and have that view only show images tagged with the same terms.

How do I do that?

Create a views block.
Under Contextual filters, add Content: Has Taxonomy Term ID
Provide Default Value -> Taxonomy Term ID from URL
Tick on 'Load default filter from node page, that's good for related taxonomy blocks' and tick your proper vocabulary.


How do I set up jumbotron so that I can control it through a panel? I am using the Panels and Panels Bootstrap modules, and I would like to have a Jumbotron block in a couple of pages.

How do I set it up so that I can control it through a panel, like shown in Drupal Restaurant: Add Jumbotron Page Banner?

So I just recently created a jumbotron functionality for a site I worked on. I used panels, bootstrap and a custom node type to achieve this and it worked pretty well.

The video from the link you provided looks like they did something similar except they have some enhancements to panels and the node creation page that may be from a custom module or another module I am not familiar with.

What you will want to do is to create a new content type called Jumbotron and add the fields you want. You could also install the Field Group module to help with getting grouped fields together.

You will need to create a new template file for that node view but I am going to assume you know how to do that to get your fields to render correctly and that you know how to use a hook_preprocess_node function as needed as well.

You can then create as many jumbotrons you want the normal way of creating nodes, and using panels, you can add the same jumbotron entity to as many pages as you want using the "Add Existing Node" option.

To get the EXACT functionality from your link I don't know if there is a  list of contrib modules to get you that without doing anything custom.

Hope that helps,


How to query all fields of the node that is tagged with taxonomy term from a specific vocabulary I'm struggling to find a way to retrieve all the node fields where a specific taxonomy is implemented. I was close to find something with this query :

$query = db_query('SELECT fci.field_name
    FROM d7_field_config_instance fci
    LEFT JOIN   (SELECT tv.vid, tv.machine_name
    FROM d7_taxonomy_vocabulary tv
    LEFT JOIN d7_taxonomy_term_data ttd
    ON tv.vid = ttd.vid
    WHERE ttd.tid = 76) AS tax
    ON tax.machine_name LIKE fci.bundle'));

But it seems like machine_name and bundle have different values for a same technology.

The idea is : From a taxonomy id => find taxonomy vid (vocabulary id) => find machine name of the vocabulary => find the bundles where this vocabulary is used.

Any help would be appreciated.

Solution  : Thanks to @Eugis' answer (Accepted answer), I came up with this solution :

db_query("SELECT fcf.field_name, fcf.data FROM
          (SELECT fc.field_name, fc.data FROM field_config fc
          WHERE fc.type LIKE 'taxonomy_term_reference') AS fcf
        INNER JOIN field_config_instance fci
          ON fcf.field_name = fci.field_name
          AND fci.bundle LIKE :bundle",
      array(':bundle'=> $bundle));

Hope it'll help someone else.

I think, you should check the field_config table where type = 'taxonomy_term_reference'.
The vocabulary name where the field is referencing to is stored in the data column as BLOB. you can use the unserialize php function to extract the data stored in the BLOB. That's because you can't reach it with a single select query.

Try using loops and ifs :)


Running "composer update" leads to errors with coder ...
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating drupal/coder (8.2.12 => 8.3.1)    The package has modified files:
    D coder_sniffer/Drupal/Test/Array/ArrayUnitTest.inc
    D coder_sniffer/Drupal/Test/Array/ArrayUnitTest.inc.fixed
    D coder_sniffer/Drupal/Test/Array/ArrayUnitTest.php
    D coder_sniffer/Drupal/Test/Array/DisallowLongArraySyntaxUnitTest.php
    D coder_sniffer/Drupal/Test/Array/disallow_long_array_d7/DisallowLongArraySyntaxUnitTest.1.inc
    D coder_sniffer/Drupal/Test/Array/disallow_long_array_d7/disallow_long_array_d7.info
    D coder_sniffer/Drupal/Test/Array/disallow_long_array_d8/DisallowLongArraySyntaxUnitTest.2.inc
    D coder_sniffer/Drupal/Test/Array/disallow_long_array_d8/DisallowLongArraySyntaxUnitTest.2.inc.fixed
    D coder_sniffer/Drupal/Test/Array/disallow_long_array_d8/disallow_long_array_d8.info.yml
    D coder_sniffer/Drupal/Test/Classes/ClassCreateInstanceUnitTest.inc

  [ErrorException]
  A non-numeric value encountered

I have tried with errors

$ composer require drupal/coder ^8.3
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package symfony/debug (locked at v4.1.7, required as ^3.4.0) is satisfiable by symfony/debug[v4.1.7] but these conflict with your requirements or minimum-stability.
  Problem 2
    - Conclusion: remove doctrine/annotations v1.6.0
    - Conclusion: don't install doctrine/annotations v1.6.0
    - Can only install one of: doctrine/annotations[v1.2.0, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.1, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.2, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.3, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.4, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.5, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.6, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.7, v1.6.0].
    - Installation request for doctrine/annotations (locked at v1.6.0, required as ^1.2) -> satisfiable by doctrine/annotations[v1.6.0].
    - Installation request for doctrine/annotations 1.2.* -> satisfiable by doctrine/annotations[v1.2.0, v1.2.1, v1.2.2, v1.2.3, v1.2.4, v1.2.5, v1.2.6, v1.2.7].

Installation failed, reverting ./composer.json to its original content.

Also tried with errors

rm vendor/ -rf
composer update
....
Writing lock file
Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package doctrine/annotations 1.2.* exists as doctrine/annotations[v1.6.0] but these are rejected by your constraint.

but always end up with other errors
Any thoughts ?

What worked is the following commands

rm composer.lock
rm vendor -rf
composer clear-cache
composer require --dev drupal/coder
composer update

with last command perhaps not needed as the previous composer command does an implicit update


Taxonomy terms manipulation on node.tpl.php I wanted to print taxonomy terms on my custom node-mytype.tpl.php but what I want is not to print all the terms as they are.

Each of these terms consists of 2-3 words. And I want to manipulate the terms as below:

term1: word1 word2 word3

I want to print this as:

  word3, word1 word2

If a node has one term it's easy and I can do this as below (of course there can be some other better way to do this):

inside node-mytype.tpl.php:

<?php if (!empty($node->field_my_taxonomy_term)) { ?>

    <?php $aut = ($node->field_my_taxonomy_term['und']['0']['taxonomy_term']->name); ?>
    <?php $exp = explode(" ", $aut); ?>

    <?php if (count($exp) == 2) {?>
    <?php print ($exp[1]); print t(", "); print ($exp[0]); print t(", "); ?>

    <?php } elseif (count($exp) == 3) {?>
    <?php print ($exp[2]); print t(", "); print ($exp[0]); print t(" "); print ($exp[1]); print t(", "); ?>
    <?php }?>

I want to print multiple terms as above. For example:

term1: word1 word2 word3

term2: word4 word5 word6

should be printed as that:

  word3, word1 word2 - word6, word4 word5

I have this:

   <?php $str = ''; ?>
        <?php if (isset($node->field_my_taxonomy_term[LANGUAGE_NONE]) && $node->field_my_taxonomy_term[LANGUAGE_NONE]): ?>

        <?php foreach ($node->field_my_taxonomy_term[LANGUAGE_NONE] as $obj): ?>
        <?php $str .= l($obj['taxonomy_term']->name, 'taxonomy/term/' . $obj['tid']) . '&nbsp;-&nbsp;'; ?>
        <?php endforeach ?>

        <?php print trim($str, '-&nbsp;'); ?>
   <?php endif ?>

The below code prints the terms as that:

  word1 word2 word3 - word4 word5 word6

What code should I use here to print the terms as I wanted?

  word3, word1 word2 - word6, word4 word5

(Drupal 7.34)

Finally I did it as shown below (thanks SO):

  <?php if (isset($node->field_my_taxonomy_term[LANGUAGE_NONE]) && $node->field_my_taxonomy_term[LANGUAGE_NONE]): ?>
    <?php $allOf=''?>
    <?php foreach ($node->field_my_taxonomy_term[LANGUAGE_NONE] as $obj): ?>
        <?php $exp = explode (" ", $obj['taxonomy_term']->name);
            $exp_last = array_pop($exp);
            $eachOne = $exp_last .', ' .implode(' ', $exp);
            $allOf .= $eachOne . '&nbsp;-&nbsp;';
         ?>
    <?php endforeach; ?>
    <?php print trim($allOf, '&nbsp;-&nbsp;'); ?>
  <?php endif ?>

This is working correctly.


Major differences between Drupal-6 and Pressflow-6? I am having a Drupal-6 site and was considering to scale it. I came across Pressflow and was wondering about the major differences between the two. I came across a similar question of Drupal-7 vs Pressflow-7 but was looking specifically for Drupal-6 vs Pressflow-6. Can anyone enlighten or share their experience of using both.

Take a look at the wiki: "Comparison - Pressflow versus Drupal".


A post var error upon webform submitting programmatically I need to update a webform submission using function drupal_form_submit.

And upon updating an error is displayed.

  This form could not be submitted because $_POST was truncated to 5
  input vars. PHP max_input_vars is 10000 and needs to be increased

I tried to increase max_input_vars value even up to billion, but it doesn't helps.

The webform is very big and complicated.

Here I can't use function webform_submission_update, because some form alter and form validation functions must be executed upon the webform submission updated.

According to this post:

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

If it's a custom webform template, you may need to add, at the end of the form:

<?php print drupal_render_children($form); ?>

See also this related issue here: https://www.drupal.org/node/2417757


Can't get hook_menu to work Can't seem to get hook_menu to work at all. I'm using the following code:

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

  $items['node/%node/mymodule-product'] = array(
    'title' => 'Edit Product',
    'page callback' => 'mymodule_product_redirect',
    'page arguments' => array(1),
    'access callback' => 'edit any commerce product entity',
    'weight' => 6,
    'type' => MENU_LOCAL_TASK,
  );
  dsm('check');
  return $items;
}

dsm() from the devel module is outputting fine when I clear the site cache, so the hook is firing, however for whatever reason the link is refusing to display on the node tabs.

Visiting any of the node tabs already displaying, outputs the following errors:

Notice: Undefined index: access in _menu_translate() (line 778 of includes/menu.inc).
Notice: Undefined index: access in menu_local_tasks() (line 1892 of includes/menu.inc).

And manually going to a page that would be defined in hook_menu outputs a load more errors in the same vein:

Notice: Undefined index: access in _menu_translate() (line 778 of includes/menu.inc).
Notice: Undefined index: access in menu_get_item() (line 464 of includes/menu.inc).
Notice: Undefined index: access in menu_execute_active_handler() (line 499 of includes/menu.inc).
Notice: Undefined index: access in menu_tree_page_data() (line 1167 of includes/menu.inc).
Notice: Undefined index: access in menu_tree_page_data() (line 1167 of includes/menu.inc).
Notice: Undefined index: access in menu_local_tasks() (line 1845 of includes/menu.inc).
Notice: Undefined index: access in menu_tree_page_data() (line 1167 of includes/menu.inc).
Notice: Undefined index: access in menu_tree_page_data() (line 1167 of includes/menu.inc).
Notice: Undefined index: access in menu_tree_page_data() (line 1167 of includes/menu.inc).

While these are all only PHP Notices, I assume they still may be relevant.

Thanks!

'access callback' needs to be a function name. The function should return TRUE or FALSE;
From the API:

"access callback": A function returning TRUE if the user has access
rights to this menu item, and FALSE if not. It can also be a boolean
constant instead of a function, and you can also use numeric values
(will be cast to boolean). Defaults to user_access() unless a value is
inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK
items can inherit access callbacks. To use the user_access() default
callback, you must specify the permission to check as 'access
arguments' (see below).
"access arguments": An array of arguments to
pass to the access callback function, with path component substitution
as described above. If the access callback is inherited (see above),
the access arguments will be inherited with it, unless overridden in
the child menu item.

This means you could ommit 'access callback' and use 'access arguments' instead:
// This will be true for users with the access content permission
'access arguments' = array('access content');


Link it's node link to the node:body in views I can only link it to it's node when its a node:title field when making a certain view. how can I link it to the node:body? Is there are reference id?

In all seriousness, you could do this by first including the node:nid in your view and then rewriting node:body as a link to node/[nid] in the configuration.  What might happen with all the content of that body inside of that though is undetermined.  I would hope views would check_plain it or remove tags etc so that just text is linked but I've never done it to see.


Is it possible to serve a theme from outside the web root? We have a need to keep a proprietary theme in a directory that isn't readable or writable by a client.

At the same time, the client needs to be able to do standard Drupal updates (ie, they will have full control of the web root of the Drupal installation, but nothing above that).

What's the easiest/best way to accomplish this, assuming it's possible?

If you have

Options +FollowSymLinks

set for the DocumentRoot for your Drupal site, you can put the proprietary theme anywhere you want as long as you create a symlink to it somewhere Drupal searches for themes (eg, sites/all/themes).

Just keep in mind that Apache needs to be able to read it.  Whether the client can read it directly is a permission issue, but if Apache can read it a savy client can get it via custom PHP.


How to export users to a CSV file? I would like to export users into a CSV in Drupal 7. I believe I can use the module Views Data Export, but I am not sure how to do that or if it is the correct module I would like.

Yes, Views data export is your best choice.

Create a view displaying users and add a page display. Add the fields you want in your export and change any additional settings you want.

Then add a display of type Data export, and set it to attach to the Page display. This way it'll add a link to the file download to that page (You can probably also skip the Page display and only add a Data export display with a path defined).

Choose your export format (CSV) under format settings. If you have a lot of users, make sure to choose batch operation under 'Data export settings'.

It's also a good idea to require a specific permission or role to access the view.


The Facebook Autopost module "user hasn't authorized the application" I have a problem with the Facebook Autopost module for Drupal 7.28): After publishing a node, I get an authorization error.

  Facebook SDK threw an error: OAuthException: (#200) The user hasn't
  authorized the application to perform this action

I have checked permissions "Publish Actions", "Publish Stream", "Manage Pages" for Administrator role in fbpermissions module.

Also, I have submitted "manage_pages" in my app but cannot submit "publish_actions" because of this:

  It looks like you haven't made any API requests to access content with
  the publish_actions permission in the last 30 days.

Don't know what to do now. Have no idea why it's not working and what Facebook app permissions are missing. Was googling it for an about 2 hours. Checked all found solutions... none of them worked...

This happens when you add any user to roles section and if the user haven't accepted the role and you are trying to post something on his behalf. first accept the role in developers page of Facebook.


how to add conditional styles? How can I insert the following:

<!--[if lte IE 9]>
    <style type='text/css'>
  #page{display: none;}
    </style>
<![endif]-->

I tried it in page.tpl.php but not worked.

Put it in html.tpl.php also it work in page.tpl.php but I think you did not clear cache , please dont forget this, clear cache after templates changes.

also you can use conditional css
this link help you

https://drupal.org/project/conditional_styles


Theme is not working when files are uploaded from localhost to the web server I have finally made it to point where i think it's ok to upload my work from localhost to a web server of mine.

I tried to upload my work from localhost to my web space (on hostgator).

My problem is that Drupal seems not to recognize the theme that is supposed to be used, including not identifying some custom template files I have written for views and nodes.

Same things work ok on localhost and page source code is generated ok (i.e. the correct path img src="http://localhost:8888/drupal/sites/all/themes/simpler/logo.png" is generated for my logo (custom)) but the same thing when uploaded on web server is not working and the path for img src is not generated at all in the page source.

I have several other problems, like custom tpl.php files (for nodes or views) are not used at all, i guess because the system for some reason does not reach (?) the /sites/all/themes/simpler .

I have tried flushing caches with no luck. Also, found some posts suggesting go clicking the 'Save changes' button in theme admin screens but no luck with this too.

If this means something, i have uploaded the whole 'drupal' folder from my localhost to my web server and switched the settings.php to point to my web servers db, which was created by importing .sql file (exported from my localhost).

Hope this whole thing makes sense and someone could help or point me to a direction.

Have you tried putting another theme as default, them uploading the database again ?
If you then try to set your theme as default on the live site, it might work...


Trying to change a radio value during form validate I have a form that includes a set of radio inputs, and other fields that will or will not be relevant, depending on which radio option is selected. I'm using #states for client-side UX sugar.

However there are certain conditions, picked up in the validate function that need to change the value the user entered for the radio, and re-present the form with a different option selected. I'm having problems with this, as the form comes back but the option is not changed. e.g. Submitting this should with 'a' selected should change it to 'b' and re-present.

What happens is that the value is set to b, the form rebuilds, but the browser still shows 'a' selected.

<?php
function x_a_form($form, &$form_state) {
  return [
    'switcher' => [
       '#type' => 'radios',
       '#options' => [
           'a' => 'Aye',
           'b' => 'Bee', ],
       '#default_value' => empty($form_state['values']['switcher'])
                           ? 'a'
                           : $form_state['values']['switcher'],
    ],
    'submit' => ['#type' => 'submit', '#value' => 'Go' ],
  ];
}

function x_a_form_validate($form, &$form_state) {
  // silly example of a condition...
  if ($form_state['values']['switcher'] == 'a') {
     // Change the value.
     // Nb. form_set_value() is a very long winded way to do just this:
     $form_state['values']['switcher'] = 'b';
     // We will not be saying anything is invalid, but we don't want
     // the form to submit.
     $form_state['rebuild'] = TRUE;
     return;
  }
  // other validation...
}

Did a little more digging. It seems when Drupal (re)builds a form, it sets the element values based on the actual form input ($form_state['input']) and not the form values ($form_state['values']). See _form_builder_handle_input_element. So form_set_value does changes the form value, but it does not update the form input and, therefore, does not get processed how you want it to in this case. While I don't know if this is the "proper" way to do this, but in your form function, you can try throwing in something like:

if (!empty($form_state['values']['myelement']) {
  $form_state['input']['myelement'] = $form_state['values']['myelement'];
}

I tried this with a textfield element, and the value I set using form_set_value was displayed in the textfield when the form was rendered.


How to print out usernames using EntityFieldQuery I'm trying to filter users using entityfieldquery (type 'user') by fieldConditions, but I don't know how to print out the usernames on a page. If I use "print_r", it works. But I don't want to print them out on a white page. ^^ If I use $output, I get only one name. For nodes, there is a function "node_view_multiple" to use it like $output = node_view_multiple($nodes);
Is there also a way for entity_type user?

Here is my code:

global $user;
$angemeldeter_user = user_load($user->uid);
$alter = $angemeldeter_user->field_alter['und'][0]['value'];
$alter_faktor = 4;
$alter_untergrenze = $alter - $alter_faktor;
$alter_obergrenze = $alter + $alter_faktor;

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
->fieldCondition('field_alter', 'value', array($alter_untergrenze, $alter_obergrenze), 'BETWEEN');
$result = $query->execute();

if (isset($result['user'])){
global $user;
$angemeldeter_user = user_load($user->uid);
$users=user_load_multiple(array_keys($result['user']));
dpm($users);

foreach($users as $value) {
  $user_list = (array)$value;
  $users[$user_list['uid']] = $user_list['name'];
  $output = '';
  $output .= $user_list['name'];
  return $output;
  }
  }
  else{
    $hihi = 'no results';
    return $hihi;
  }
}

Since user_load_multiple() returns an array of user objects you need to use the '->' in order to access them.

$output = '';
foreach ($users as $key => $value) {
  $output .= "index: $key; name: $value->name<br />";
}
return $output;


How do I make variables available for all blocks in a page? In my website I have an inc file containing some values that are needed on all blocks of a page. For reasons related to the performances, I would like not to use the php "require" function in each block. Is there a way to load this file at page level and make the values available in all blocks?

Do I have to do that in the template_preprocess function?

Yes this can be done in hook_preprocess_block.

inc file:

function get_some_vars() {
  static $vars = array();

  if (empty($vars)) {
    $vars['foo'] = expensive_function_1();
    $vars['bar'] = expensive_function_2();
  }

  return $vars;
}

.module/template.php file:

function MYMODULE_preprocess_block(&$vars) {
  require_once 'my.inc'; // or module_load_include, depends where your code is

  $vars += get_some_vars();
}

It's not the exact desired workflow you described in the question, but it has a similar effect; require_once will only include the file once per request, and the variables will only be prepared once per request. There is the function call overhead, but given that themes don't have the concept of always-available-vars (as far as I know each theme call is an isolated instance as it were), I think this is the closest you'll get without patching the theme system.


How so I execute $query->orderBy('FIELD(node.nid, 5,12,3,6)', 'ASC')? I am currently converting code from Drupal 7 to Drupal 8. So far I am unable to find resources on how to convert the call to orderBy() which uses an expression.

$query->orderBy("FIELD(node.nid, '5,12,3,6')", 'ASC');

Based on D8 Select::orderBy, it only accepts alias or fields.

What is the code I should use in Drupal 8?

I did a workaround by implementing a CASE statement then sorting by the value.

$query->addExpression("
    CASE node.nid
        WHEN 5 THEN 1
        WHEN 12 THEN 2
        WHEN 3 THEN 3
        WHEN 6 THEN 4
        ELSE 5
    END
", 'order_field');

$query->orderBy("order_field", 'ASC');

Hopefully they'll add another function to handle these special statements in the future.


Token Filter module to work on Menu URL and Title menu_token module is working fine to achieve the purpose. Does the module token_filter has this functionality? I can use tokens in wysiwyg using token_filter but cannot make it working for menu title or url since there is no setting I could find. Since the comment in drupal issue says that it was solved using token_filter module, I want to know the way it was achieved.

No, not by itself. The Token Filter module's functionality adds a token input filter to text formats in Drupal. The only field types that can use text formats are the 3 Text (formatted) field types, not the Link field type.

One can only speculate on the comment's solution you refer to. Text Formats/Input filters are designed to allow HTML input that should be filtered for presentation. It would be an odd-use-scenario to apply that to a link field.


Add default image to image file programmatically I am trying to add a default image to an image field in Drupal 8 using the configuration management interface (CMI).  Normally once I have a field configured through the admin UI, I would then export the config YAML file for that field so I can add it to my custom module. The issue is that the default image for an image field is content and cannot be directly exported.

If I do export such a file, it would look like this:

langcode: en
status: true
dependencies:
  config:
    - field.storage.node.field_bluescope_header_bg_image
    - node.type.bluescope_page
  module:
    - image
id: node.bluescope_page.field_bluescope_header_bg_image
field_name: field_bluescope_header_bg_image
entity_type: node
bundle: bluescope_page
label: 'Header background image'
description: 'Image used as the page''s header background'
required: false
translatable: false
default_value: {  }
default_value_callback: ''
settings:
  file_directory: images/header-bg
  file_extensions: 'png gif jpg jpeg'
  max_filesize: ''
  max_resolution: ''
  min_resolution: ''
  alt_field: true
  alt_field_required: true
  title_field: false
  title_field_required: false
  default_image:
    uuid: 8288b3b1-4b0e-4efc-9137-55cb68382f0a
    alt: 'Header background image'
    title: ''
    width: 1920
    height: 1080
  handler: 'default:file'
  handler_settings: {  }
field_type: image

I noted that the default image is referred to using a uuid.  I was thinking that I could address this by programmatically adding the default file to this field's configuration during the module install process. What I tried was to create the image in drupal's file system and then get the uuid of that file and add it to the fields configuration using configFactory:

function colorbond_data_install() {
  $config_factory = \Drupal::configFactory();
  $field_bluescope_header_bg_image_config = $config_factory->getEditable('field.field.node.bluescope_page.field_bluescope_header_bg_image');
  $default_image = $field_bluescope_header_bg_image_config->get('settings.default_image');

  // Create default image file.
  $file_info = colorbond_data_add_file('public://images/header-bg/', 'starwars.jpg', 'Header background image');
  $file = File::load($file_info['target_id']);

  $default_image['uuid'] = $file->uuid();
  $default_image['alt'] = 'Header background image';
  $default_image['title'] = 'Header background image';
  $default_image['height'] = 1080;
  $default_image['width'] = 1920;

  $field_bluescope_header_bg_image_config->set('settings.default_image', $default_image);
  drupal_flush_all_caches();
}

The problem is that when I reinstall the module, the default image configuration does not appear:

Not sure what I am doing wrong.

Add ->save(TRUE); as in $field_bluescope_header_bg_image_config->set('settings.default_image', $default_image)->save(TRUE);


How can I create a custom service? I've been following instructions on the web on creating a new service, but I can't seem to get it to work.

In my controller:

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

class MyController extends ControllerBase {
  public function myroute() {
      $db = \Drupal::service('mymodule.db');
      return array('DEBUG');
  }
}

In my mymodule.services.yml:

services:
  mymodule.db:
    class: Drupal\mymodule\mymoduleDB

In my service class:

namespace Drupal\mymodule;

class mymoduleDB {
  public function dosomething() {
    return 'data...';
  }
}

In my controller, when I comment out the line that calls \Drupal::service, then the controller works, so it's an issue with calling the service.

I'm getting a HTTP 500 error.

Create mymodule.services.yml

services:
  mymodule.custom_services:
    class: Drupal\mymodule\Services\CustomService
    arguments: []

Now create Services folder under your mymodule/src. After that create CustomService.php in Service folder.

In CustomService.php

<?php

namespace Drupal\mymodule\Services;

/**
 * Class CustomService.
 */
class CustomService {

  /**
   * Constructs a new CustomService object.
   */
  public function __construct() {

  }

  public function getServiceData() {
    //Do something here to get any data.
  }
  /**
   * Here you can pass your values as $array.
   */
  public function postServiceData($array) {
    //Do something here to post any data.
  }
}

And for accessing service in your module file

$service = \Drupal::service('mymodule.custom_services');
$service->getServiceData();


How do I find a vocabulary ID for use with tokens I need the Id for tokens. I know in Drupal 7 it is based on the label but when using tokens for rules the label doesn't work in the identifier. I don't need to find it programmatically. Is there another way?

Sure, just pop into the taxonomy_vocabulary table in the database and see what vid is associated with the correct vocabulary.

For the record if you do need to get it programmatically you can do so like this:

$vocab = taxonomy_vocabulary_machine_name_load('vocab_name');
$vid = $vocab->vid;


Multi step registration - save on last step I'm using the module Multi-Step Registration module. The problem is that the user is saved after clicking the continue button on the first step. So when a user quits after 3 steps the user is saved already ... (but the registration process isn't completed).

Does anyone have an idea how I could the save the user on the last step or a workaround to fix this?

You could consider one of two modules that force users to complete their profile if they've dropped off halfway thorough, but still created the account:

Complete Profile or Profile Fields Force Filling

Or, roll your own form using ctools.


in multi-site do you set base url for each sites settings? Have just enabled security review module and it's alerting to base url not being uncommented and set. This is a multi-site so do I need to set the base url in each settings file for each site? I set the base url in settings for the root site but the alert still came up for subdomain of multisite where have not changed its settings file.

To be more secure you should set the base url for each site, yes.

Setting this helps protect against a phishing attack where a malicious user manipulates Drupal's use of the host request header to make the site provide incorrect links.


Postpone payment to a later stage How would it be possible to postpone payment processing (move out of checkout) to a later stage/order status change?

I always thought the payment processing is a rule to be invoked on checkout completion, that I could easily modify, but as it comes out, no such rule can be found.

I'm using Stripe payment gateway with card on file. How I'd like the process to work is that the user puts in the card information in checkout as usual (because of card on file, the information is tokenized and a token stored to my server) But instead of the payment happening right away, I'd like to invoke the payment for the order only after the order has been fully processed and sent on it's way.

Therefore I'd like to ask, what would be the recommended process for achieving such functionality?

My ideal solution would be to somehow skip the payment processing in checkout, and process the payment with a rule on another order status change with the card data stored, but am currently unable to find solutions for this.

Best,

Alari

the payments usually are done in the same session then the checkout and has to be done by the user.

some gateways allow batch processing of payments, maybe try another payment gateway ?

or change your business logic. refunding is easier in most gateways ;)
so the user pays, but gets refunded, if the order is not processed after X days.


How can I render an HTML table in a block? i have created a module for showing third party API data

here is some data returned from that API

{"ObjectId":43,"ObjectName":"MEGA MELA","ObjectTitle":"Event Created by API","ObjectDescription":"NEW EVENT BY API","ObjectLabel":"","ObjectTypeId":33,"MaxFieldsExpected":5,"ObjectValueType":null,"ObjectControlType":"","IsDeleted":true,"CreatedDate":"2019-05-22T07:56:03.767","CreatedBy":null,"EditedDate":null,"EditedBy":null,"DeletedDate":null},{"ObjectId":44,"ObjectName":"Event x11","ObjectTitle":"Event Created by API","ObjectDescription":"NEW EVENT BY API","ObjectLabel":"","ObjectTypeId":33,"MaxFieldsExpected":5,"ObjectValueType":null,"ObjectControlType":"","IsDeleted":true,"CreatedDate":"2019-05-23T00:33:50.7","CreatedBy":null,"EditedDate":null,"EditedBy":null,"DeletedDate":null}]}

i have created a custom module to show some of  this data in a block

this is my module directory hierarchy , module directory name is apihtml

 -apihtml
    -src
      -Plugin
        -Block
          -rest.php

    -apihtml.info.yml

as you can see there are just two files
  apihtml.info.yml and rest.php

here is apihtml.info.yml content

 name: Third Party Api Data with html
    type: module
    description: 'This is for showing rest data in ui with html'
    package: Custom
    version: 8.x
    core: 8.x
    dependencies:
      - node
      - block

and here is rest.php content

   <?php

/**
 * @file
 */
namespace Drupal\apihtml\Plugin\Block;
use Drupal\Core\Access\AccessResult;

use Drupal\Core\Block\BlockBase;
use Drupal\Component\Serialization\Json;

/**
 * Creates a 'Foobar' Block
 * @Block(
 * id = "AntShow with html formatting",
 * admin_label = @Translation("Ant Show & HTML"),
 * )
 */
class rest extends BlockBase {
 public function build() {
    /** @var \GuzzleHttp\Client $client */
    $client = \Drupal::service('http_client_factory')->fromOptions([
      'base_uri' => 'http://myApiPath',
    ]);

       $response = $client->get('objects/events');

    $dec = Json::decode($response->getBody());

    $items = [];

foreach ($dec as $d) {
    foreach ($d as $ins) {
  $items[] = $ins['ObjectName'] ;

    }
}

         return [
      '#theme' => 'item_list',
      '#items' => $items,

    ];

  }
}

here by using array  Key ObjecName i am able to show object name in block

here is the block OutPut

MEGA MELA
Event x11

but i want something more
i want to show this API returned data in the tabular form   means the array key should be the header  of the data value data will be in rows

like this

   ObjectId  | ObjectName | ObjectTitle           | ObjectDescription | ObjectLabel | ObjectTypeId | MaxFieldsExpected | ObjectValueType | ObjectControlType | IsDeleted | CreatedDate | CreatedBy | EditedDate |  EditedBy
    43        |  MEGA MELA |  Event Created by API | NEW EVENT BY API | ..............................................................................

in this Drupal block all the data displayed has to be returned  in build function in rest.php file

this is the code which shows data returned by api in tabular format

     foreach ($dec as $d) {
  ?>

<?php foreach ($d as $ins) { ?>

<?php
 foreach ($ins as $key=>$value) {
   echo "
".$key."
	";
 } ?>

<?php
 foreach ($ins as $key=>$value) {
   echo "
".$value."
	";
 } ?>

<?php
} ?>

 <?php
}

But i am not getting how can i put this code in build function of rest.php to show tabular data  in the block

You can use the table theme type to do this.  In your build section, return a render array that includes this:

return [
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
];

Where header is an array of strings and rows is an array of row value arrays.

Some reference items I found:

New render element #type 'table'

Render arrays


Change height of CKEditor (per profile) without using WYSIWYG Module Problem

How can I change the height of the CKEditor window without using the solution outlined here which requires the WYSIWYG module. I can't spot where the height is defined in the CK module.

Ideally I'd like to be able to set it per profile and I'd prefer not to add an extra module if possible.

Has anyone dealt with this before?

UPDATE:

The patch in this thread on DO fixes this issue.

Looking at the ckeditor demo on this page it is possible to change the height of the editor with css alone.

The div .cke_contents has an element style setting the height to 300px, however a rule in the stylesheet marked as important would overrule this.

So, if you can add the roles of the user as a classes of say the body, then you could include:

.role1 .cke_contents {
    height: 400px !important;
}
.role2 .cke_contents {
    height: 100px !important;
}

Alternatively there may be a class added by the CKEditor profile type that you could use.


Drupal embed view in email sent by views I've configured a rule to send an email after a commerce order is placed containing products of a particular type. That works fine. The body though is a view token ([views:embed:golf_registration_information:default]) pulling in specific order info (couldn't do this through the rule with the info I wanted to include). However in the email, I'm getting "edit view" links in a few places, which obviously I don't want.

Here's what the link looks like: http://website.com/admin/structure/views/view/golf_registration_information/edit/default?destination=checkout/451/paypal_ec

I can't figure out how they are getting in there. Is there a setting I'm missing in Views? It appears as the first thing in the body, and then within the body above the line items table. Obviously I didn't add anything within the Global Custom Text field that's outputting the fields.

Modules I'm using: D7, Commerce, Commerce Rules Extra, Rules, Mimemail, Views, Token Embed Views

Sounds like you need to disable contextual links:


How to change HTML output of main menu When I output the main menu this is the html that gets generated:

Home

Page

page

However I'd like to completely restructure the menu like this:

                    SIGN UP
                    LOGIN
                    <a class="main-nav__button animate grid__item xl--1-5 l--1-5 sp s--tbp t--tbp" href="<?php echo $front_page; ?>">HOME
                    LINK 1
                    LINK 2
                    LINK 3
                    LINK 4

How can I change the html output of the menu as well as the links inside?

Ideally I'd like to output any menus as a  element and be able to pass classes and an id to each one, the same also goes for the links inside.

Also the first two links in the menu are login and signup buttons which only display at certain screen sizes and have completely different classes to the rest of the menu links. Is this also possible to do?

I have tried altering the theme_menu_tree and theme_menu_link functions but am having no luck as I am somewhat of a beginner in PHP and Drupal.

Most likely that your theme renders them menu either in theme_preprocess_page() in its template.php and passing it page.tpl.php. That's how Garland does it:

https://api.drupal.org/api/drupal/themes%21garland%21template.php/function/garland_preprocess_page/7

https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_links/7

Given your question, you're most likely going to end up with a custom theme, which is normal for most sites. The best way to tackle this is to change the logic in preprocess_page to set it up how you like.

That's more sustainable and specific than altering or overriding theme_links() globally in module-space.


How do I add the JavaScript src file inside a block? I have called the JavaScript source code, <script scr=""></script>, inside a block. And this code is working fine.

But I am not sure whether it's good practice or not.

If it's not a good practice, give me some suggestions for adding above code inside the block.

You should add javascript as a library, then attach it to your block in the build array or a preprocess function like this:

$block['#attached']['library'][] = 'mymodule/mymodule.search_filters';
$block['#attached']['drupalSettings']['mymodule'] = [
  'cats' => 'tabby',
  'dogs' => 'dalmation',
];


Dependency fields on add people page For a project I need to register new customers. That customer belongs to a store chain, and that store chain is connected with a store.

I only want to display the store's which are linked to the storechain on the add people page.

What is the best way to fix this? Conditional fields module doesn't work for this :(

Thanks in advance!

perhaps the Profile module create a profile per store and then show the right store profile fields on the registration page, if needed to work with your logic you could place specific stores on specific registration paths with Profile2 Registration Path.

EDIT

  What is the best way to fix this? ... big changes like this aren't possible ...

You asked a problem, I offered a solution. My opinion on the best way to fix your problem is to do some re-engineering of your site. If you disagree that's fine -- best of luck on finding a solution to your problem.

Modules such as views bulk operations, Rules, Node Convert are examples of modules which exist to make sweeping changes of a website feasible (although not without coordination on your behalf). What you say isn't possible -- I say is merely difficult.


How do I block a user/cancel a user account in Simpletest? I'm trying to write some tests for a module for situations in which a user is blocked.  I know I can use drupalCreateUser() to make new users, but how do I block a user I have created in Simpletest?

Once you've got the user object back from drupalCreateUser() you can use standard API methods to make changes (in this case user_save()):

user_save($user, array('status' => 0));


How do I use the login for an external application? Long ago I built a php based application for room reservations which basically ran on its own – outside the website's CMS. It was part of what I would now call a custom made intranet – or "custom-app".

Now the main website finally runs on drupal – but now we have the drupal login and the custom-app login. How could I now 'teach' the custom-app to accept visitors that are already logged in to the dp based CMS?

I know, the 'easiest' or actually 'most correct' way of doing this would probably be to develop the custom-app into a module. But are there other ways e.g. to pass the login information over to the custom-app? Any pointers would help. Thank you!

update1: both are running on the same server under the same domain.

update2: I finally came across this question "How to call drupal_bootstrap from custom file in subfolder?" – I guess going bootstrap would be the right direction for now…

You can install in your drupal site a contrib module which allow you to create an API which can access another modules.

You can use Services module which implements route to allow users login across external sites, and another route to get the current user logged in.

So you can install this module and enable this routes, and with your php site make http calls to this sites to log in the user and check if he is logged in.


Build a form with multiple choice answers (multiple submit buttons) and validation Requirements:

User navigates to path "new-problem" and is presented with a math problem and multiple choice answers, one of which is correct.
There is one submit button per choice
If the user clicks a wrong choice, we record that to the database and the same problem is shown again (user gets another chance)
If the user clicks the right choice, we record that to the database and a new problem is shown.

I haven't been able to coax Drupal to accomplish this thus far. I'm sure the problem involves how the form is/isn't rebuilt. I believe this to be related to Submitting a form rebuilds (expensive) page upon submit

I tried using a validation function and form_set_error() when the user chose a wrong choice, but the form kept being rebuilt from scratch with a new problem (instead of the same problem). I tried setting $form_state['rebuild'] = TRUE to no avail.

The code below works except for the first time. When a user navigates to "new-problem", he is shown the form. Upon clicking an incorrect choice's submit button, the "incorrect" status message is shown, but a new problem is shown. Thereafter, clicking an incorrect choice correctly shows the"incorrect" status message and the problem he got wrong.

hook_menu()

function dfm_menu() {
  $items['new-problem'] = array(
    'page callback' => 'dfm_new_problem_page',
    'access callback' => TRUE,
  );

  return $items;
}

menu callback

function dfm_new_problem_page() {
  $node = dfm_get_new_problem(); // Returns a "problem" node

  return drupal_get_form('dfm_problem_form', $node);
}

form builder

function dfm_problem_form($form, &$form_state, $node) {
  $form['#nid'] = $node->nid;
  $form['#correct_choice'] = $node->field_correct_choice[LANGUAGE_NONE][0]['value'];

  $problem = $node->field_problem_mathml[LANGUAGE_NONE][0];

  $form['problem'] = array(
    '#prefix' => '
',
    '#markup' => check_markup($problem['value'], $problem['format']),
    '#suffix' => '
',
  );

  $i = 0;

  // One submit button per choice
  foreach ($node->field_choice_mathml[LANGUAGE_NONE] as $choice) {
    $correct = ($i == $form['#correct_choice']); // TRUE if this choice is the correct choice

    $form['choices'][$i] = array(
      'button' => array(
        '#type' => 'submit',
        '#value' => t('This one!'),
        '#submit' => $correct ? array('dfm_problem_form_submit_correct') : array('dfm_problem_form_submit_incorrect'),
      ),
      'mathml' => array(
        '#markup' => check_markup($choice['value'], $choice['format']),
      ),
    );

    $i++;
  }

  return $form;
}

incorrect submission handler

function dfm_problem_form_submit_incorrect($form, &$form_state) {
  // Create a new answer node to record the incorrect answer
  dfm_record_answer($form['#nid'], $form['#correct_choice']);

  drupal_set_message(t('Incorrect'), 'error');
  $form_state['rebuild'] = TRUE;
}

correct submission handler

function dfm_problem_form_submit_correct($form, &$form_state) {
  // Create a new answer node to record the correct answer
  dfm_record_answer($form['#nid'], $form['#correct_choice']);

  drupal_set_message(t('You got the last problem right!'));
}

Thanks for your time!

I recommend using one of these two modules and adjusting them according to your needs.

https://www.drupal.org/project/quiz

https://www.drupal.org/project/field_quiz

The Field Quiz module provides a simple field that can be used as a simple quiz or multiple choice questions. It provides a field with a textfield and an checkbox combined. If added to a content type the editor of the node can enter multiple answers in the textfields and determine which answers are correct.


Create form without JavaScript I'm quite new in Drupal and I have to create a register form with dropdown lists like (Country->Province->City) but I can not use javascript, jquery or ajax due to accessibility issues. Is there any way to create it?

Some tips are welcome!

No, not really. JavaScript is the only way to have content (including forms) change on a page without relaod. Now you have two ways to go around it:

Make all choices available in all 3 downloads and only hide unneeded ones using JavaScript. That way if someone will not have JS enabled, he will see all choices and will be able to make his selection. Don't forget to test if his selection is sane on the server side!
Use multi-step form. See this question and accepted answer. That way you will be able to ask one thing at a time, serving new steps using good old HTTP.


Show cart block in pop up I've installed Drupal Commerce module, I got show cart block in header. If I click on it takes to cart page. I need a pop up of cart page on clicking show cart.

Try the Commerce Ajax Add to Cart module.

  Using this module you can ajaxify the add to cart operation. The updated cart
  will be displayed without page refresh and a popup message will be shown after you add an item to cart. You can customize the look of the blocks using its template files.


Drupal updating form fields on file upload I am trying to update form fields based on an uploaded file. Specifically, the text that is displayed on the webpage.  If the user then presses a submit button, these values are then passed to hook_node_submit() and saved in the database. I'm using hook_form_alter() to perform these updates, and I have found that I can change the default_value of a field when the webpage is first loaded. However, when the upload button is pressed by a user, and hook_form_alter() is called again, the same operation does not work. For instance,

function mymodule_form_alter(&$form, &$form_state, $form_id){
   if ($form_id == 'mymodule_node_form'){

       // I can change the default value here
       $form['field_myfield']['und'][0]['value']['#default_value'] = "Some Value";

       // Check to see if the upload button has been pressed
       if (array_key_exists('clicked_button', $form_state))){
           $trigger = $form_state['clicked_button']['#value'];

           if($trigger == 'Upload'){

               // Try to change the default value here.  The value is changed in $form,
               // but the field is not updated on the website.
               $form['field_myfield']['und'][0]['value']['#default_value'] = "New Value";

               // try changing the value after_build
               $form['#after_build'][] = 'mymodule_after_build';
           }
       }
    }
}

function mymodule_after_build($form, &$form_state){
    $form['field_type']['und'][0]['value']['#value'] = 'New Value';
    $form_state['values']['field_type']['und'][0]['value'] = 'New Value';
    return $form;
}

Do I need to perform some sort of refresh on the form? I briefly looked at AHAH, is this something that I need to use?

I am new to Drupal so I apologize in advance if there is something fundamentally wrong with this approach.  Any help is greatly appreciated.

Edit:

I added some code trying to use an after_build function to change the cck values.  This still doesn't change the value that is rendered on the website.

After many hours, I've found a solution!  Thanks goes to Matthew Davidson, who posted this workaround on drupal.org, full post The working code looks like this:

function mymodule_form_alter(&$form, &$form_state, $form_id){
   if ($form_id == 'mymodule_node_form'){

       // create a button to populate the form
       $form['mymodule_pop_btn'] = array(
           '#type' => 'submit'.
           '#value'=>t('Populate Fields'),
           '#submit'=>array('mymodule_populate_fields'),
       );
    }
}

//function to populate the form fields
function mymodule_populate_fields($form, &$form_fields){
    $form_state['input']['my_field']['und'][0]['value'] = 'Some New Value';
    $form_state['rebuild'] = TRUE;
    $form_state['no-cache'] = TRUE;
}


Add field date to node tpl I'm using a template that has this on the portfolio.tpl:

But I don't want to display the date of node created.
So, I added in the content type portfolio a field "date_field" (please see picture)

What I need now is to display this field on the tpl, replacing the "$node->created".

This is what I tried:

But it doesn't work.

How can I accomplish this?

Make sure that the field is visible under 'Manage Display' for the view mode you are working with.

If you setup the field to display in a format you like you can also just do this in your template file (instead of the format_date() part):

<?php print render($content['field_date'] ?>

In any case make sure that you also do the following before $content is rendered:

<?php print hide($content['field_date']) ?>


Does "exclude from display" on views affect performance? I really wonder if it differs in calculation time to exclude an item from display.

For example:

I have 500 rows in a view.
Each row has two fields: title and author.

Does generating the same view with excluded "author" field takes the same time as displaying "author field"?

You should profile this and see.  It totally depends on your system.

Install the Devel and Performance modules.  Then enable the Query log (in the D7 version it is at "admin/config/development/devel").  Visit some view pages, and look at the queries at the bottom of the page.  Tweak your views and re-run.  Just be sure to disable caching (including MySQL query caching) when you do this, as it may skew results.

You can also copy/paste the SQL from the view config page (enable from "admin/structure/views/settings"), into Query Browser or another tool and look at the execution time.  If you do this, bypass the query cache, to make sure you get accurate results.

Also keep in mind that buffer sizes, etc, can affect results since data may or may not need to be read from disk.  You should really have an optimized MySQL instance before you profile.


How to stop / hijack a infinite redirection loop with a redirecting rule I'm using Rules and Detector module to prevent IE < 7.0 users from browsing the site.

I've setted up a rule, executed when UA (Detector) properties are loaded. Dependings on user agent value, the rule have an action, which consists in redirecting user to a particuler node (explanation).

This works well, so well that redirection is always active, even on my destination node. So it lead me to kind of 'Too much redirection error'.

I don't manage to put another condition, like Path has url alias; that will prevent all undesired redirections.

Do you know what I'm doing wrong?
Please, don't hesitate to suggest me another way to achieve this redirection properly.

You might want to consider a simple redirect in .htaccess

To redirect based on user agent, if not already on redirected page.

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} MSIE [1-7]
RewriteCond %{REQUEST_URI} !^/upgrade/
RewriteRule .? upgrade [L]


How to perform calculations using a field from another content type? I have a spreadsheet as in the screenprint below:

Here are some details about the screenprint above:

I have 2 content types: Product and Invoice.
It consists of 3 datablocks:

Product: a table with 4 columns, and 1 row for each available product, such as the price for each product.
Invoice: a table with 4 columns, and 1 row for each invoice, which includes the total invoice amount, which is the quantity sold for a product, multiplied by the price of the product (derived from the product data block).
Total income per product, which is like a join of some of the columns of the Product data block with the Invoice data block, and to which "Subtotal" and "Page Total" row were added.

Any suggestions about building the equivalent of this spreadsheet in Drupal?

You can go for Views Calc or Views Aggregator Plus

This module adds simple calculations to a views table.

You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns.


How can I Pass a javascript variable value to PHP in Drupal 7 I am currently working on a project where i am required to pass Javascript variable value to php, i am able to do it vice-versa but unable to accomplish, this one.
Is there any way to get this done in Drupal 7 ?

If you want to pass the value during loading page. You can do it by appending the JS value as query variable in path (e.g. http://www.example.com/new/page?demo=true) for requesting the next page. In PHP, you can use API drupal_get_query_parameters to read the data.

// retrieve data from www.example.com?data=value
$query = drupal_get_query_parameters();
$value = $query['data'];


Drupal7 GMAP module, show and hide certain markers I am using GMAP module on Drupal7 for Google Maps. I am using it with Views module. Have created map view with markers from content type. Everything works fine.

Now I want to be able to show and hide some markers (not all) based on for example some category or any node field. How can I manipulate (just show and hide some of them) markers outside the view? Or maybe there is a possibility to do it within view?

Thanks.

I was able to show and hide specific markers on my full map under Administration » Structure » Views » Full Map View. I added a filter that showed markers based the Content: Author uid. Then I set the pages I wanted to show to have one author and the other locations that I didn't want to display to a different author. This article helped me figure it out: https://groups.drupal.org/node/19614

Hope that helps you.


How might I go about flagging a post or comment containing certain keywords? I have nodes coming in via FeedAPI and direct user submission, and I've got comments. A client requires me to check incoming nodes against a watch list of keywords. The posts and comments don't need to be blocked, because the watch list is fairly expansive (~1000 words but many are very context dependent). Rather, I need to be able to check the contents of a post or comment against the list and set a flag that triggers a notification to a moderator, who will manually review the content.

Is there a module that can help me with this? Barring a module, I could use a few clues to get me started on this, e.g.

"To check the content on a newly published node or comment, you could do these things."

"To flag based on a hit, you could do this thing."

Look at hook_node_xyz (d7) or hook_nodeapi (d6) to add code after node save or update.