Is there anything inherently wrong with mutually reliant custom modules? The custom modules on the main site I work on evolve.   I try to separate their functions and write multiple modules based on discrete needs but sometimes they grow into each other once written.

Now I have two modules that are inextricably linked to each other to the point where each of their .info files have dependencies[] = theothermodule in them to remind future site admins of this fact.

Of course I can undo this and separate the functions out, but thinking about it made me wonder why I should do it, and that advice on this topic might be useful here.

From wikipedia on "modular programming"

  Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules

If you have two modules, and they depend on each other, they are no longer independent, and in fact, are no longer two modules, but one.
At least in theory, that's a bad thing, because you can no longer make changes to one, without changing the other.

Sooner or later, you'll also likely find that this becomes a practical problem, because as the module grows, it becomes increasingly difficult to keep up appearances of an external interface. Both modules are calling functions in both modules, and again, you can no longer change one without also updating the other.


Theming: Is this a valid way to go about it Total newbie at Drupal. Is it valid to say that I could code a page in pure html/css and then start adding the php variables needed to eventually make the page.tpl.php?

Or should I go about it by creating the tpl.php file differently?

That feels possible but all the reading I've done hasn't explicitly said it that way.

You certainly could do it that way, however, that would require you to know all of the php necessary to make a fully functional Drupal page.tpl.  What I would recommend, and how I started themeing (outside of reading a bunch!) was taking a page.tpl.php from a theme similar to what I was looking for and modifying it until I was happy with it.  After doing this several times and experimenting a lot (and reading!) I became quite familiar with the templating system used in Drupal and the php code needed in the most common template files.


How to change the alias for the core forum landing page for drupal 6? Core forums sets the landings page to /forum. I need this changed to /some-other-name.the forum posts can be changed using pathauto, but I need to change the alias for the top-level forum landing page. I have tried playing with url aliases but can't find anything to solve my purpose.
I googled and found this exctly same question on drupal stackexchange, but I need to do it for drupal-6. Please help.
 Edit: im also using advanced-forum module

As Jimajamma commented, the answer was really simple.. just go to admin/build/path/add and in the existing system path I entered forum and in the path alias I entered /some-other-name and it worked, and btw if you need it for drupal 7, the go to admin/config/path/add.


How to disable adding new terms via the autocomplete deluxe module for taxonomy terms? I'm using the autocomplete deluxe module for taxonomy terms in my fields. I want to prevent users from creating new terms during content creation. How can this be done?

You can use the content taxonomy module: https://www.drupal.org/project/content_taxonomy

On the content type fields that are taxonomy reference fields there will now be an extra option that says: Deny any new terms checkbox

It will throw this error when creating a new term:

Client: new terms are not allowed. Please choose from the suggested options.

Apparently there are other solutions I found aswell:

https://www.drupal.org/project/taxonomy_autocomplete_permission -- but it isn't working for autocomplete deluxe.

And there were a few discussions where it involved hacking core to disable it. The content taxonomy module seems to be the only way. It would be better if we didn't have to install another module.


Is there a bulk method of doing 301 redirects from old nodes to new node pages? I am updating an old drupal 7 site and many of the old nodes now have newer counter parts with new nodes. Since alot of my old nodes have already been spider-ed, I want to do a 301 redirect to the new nodes. I'm currently doing it manually by deleting the old node and then copying the URL alias into the redirect module and redirect it to the new node path. Is there a easier way to do this if I have 1000 nodes that need redirection?

Redirect Module + Path redirect import Module

The module Redirect has great options, one of which creates redirects when you rename a page and hence change an alias.

The module Path redirect import works with Redirect and allows you to upload a CSV of redirects (or use Drush), it even checks if a page you are redirecting to exists.


How do I update commerce product display nodes based on SKU (of the referenced product)? I would like to update the product display nodes with taxonomy terms based on the SKU of the referenced product of each node. Is that possible, programmatically?

I know the SKU.
I need to find the product by the SKU of a product display.
1.I update the taxonomy term of the product display accordingly.

I tried to use EntityFieldQuery without success.

If someone could possibly give me an idea on the best approach to do this in DrupalCommerce, or provide a link to the documentation I have missed, it is greatly appreciated. I have lost a day or two googling the wrong questions, apparently.

Although an old thread, for the benefit of others looking, this could be done easily using views_bulk_operations (VBO). No coding required.

Install VBO.
Create a View of product display nodes.
Add a relationship to commerce product.
Add a batch update operations field to the View.
Enable the "Modify entity fields" option in the VBO field settings.
Add an exposed filter for the product SKU
Save
Use the batch update operation to check and set the relevant taxonomy term reference field.


How to set field values when creating new node with Rules? We can create new nodes using Rules Actions. However, when creating new nodes, if we want to set the fields' values for the new node, there seems to be no way to do that in Rules.

E.g. I want to create a new node, using Rules Action, which has a field field_age. And I want to set it to some value depending upon the event. How do I do this?

Can this be done using Rules?

Yes you can.

Add action: Create a new entity >> select your content type

Add action: Set A Data Value and for data selector use, for example if want to set a value for the body then you use: entity-created:body

In your case entity-created:field-age

Add action: Save Entity >> entity-created


Custom Pricing based on anonymous customer input Hi gurus and fellows,

I am a newbie at DrupalCommerce, though I have been designing website for a while using Drupal.

For our new project, we need to provide some custom pricing rules, based on user input. Anomymous user fills in a form, and, based on his input, we compute some special 'discount' (sort of).  Let me emphasize that user is not connected (registered), and its data is kept in session only.

As far as I know, we need to set up some "Pricing Rules", but to tackle my problem, I can only see "User has role" / "User is blocked" in the possible conditions, which address only logged-on users.

How you would you do that ?
Do I need to write up a custom rule ?

Any hints much appreciated.

Thank you.

User has role can indeed be used to setup a rule for Anomymous user, see the image:


Server Error 500 on every Ajax Call we have a problem that we get a internal server error on about every ajax call. The example below happens when editing a view clicking "add filter" and directly click on abort. It also happens when making changes to a view. At first glance the change seemed to be ignored but after refreshing the pages the changes will be visible.

When accessing the URL which throws the error we get a valid json string (checked with jsonlint.com).

Our server logs sadly show nothing interesting. I would appreciate any kind of hint where to look for a solution.

Edit:
The nojs version seems to work fine but that's no solution in the long term :/

Look at your PHP error log. It should give you the file and line number it's having an issue with.

If you can, copy and paste the last few lines of the error log on here for us to look at.


Many items in one table cell I have a very complicated view, and I can't change the existing field structure (it's an established and functioning site). This is a simplification of the problem, but it has to happen this way, I can't turn it the other way around...

There are two node types (Author and Book), the Book type has an entity reference pointing at the Author.

The view I want to create lists the authors and needs to display all the Book titles in a single column (one author per row, all the book titles in one cell together).

How do I create the entry in the view, so it does that?

You might be able to get the result you want using the Views Aggregator Plus contrib module.

It's still in alpha for Drupal 8, but it allows you to group and aggregate results.


Added ajax to a Link but its not working I added a class use-ajax to a link but Its not updating the wrapper `div. My Code is:

function custom_menu(){
  $items['testing'] = array(
    'page callback' => 'articlenodeform',
    'access arguments' => array('access content'),
  );
  $items['customajaxcallback'] = array(
   'page callback' => 'custom_ajaxcallback',
   'access arguments' => array('access content'),
  );
  return $items;
}

function articlenodeform(){
   drupal_add_library('system', 'drupal.ajax');
   drupal_add_js('misc/ajax.js');
   $link = l(t('Say Hello'), 'customajaxcallback/ajax', array('attributes' => array('class' => 'use-ajax')));
   return '
'.$link.'

';
}

function custom_ajaxcallback($type = 'ajax') {
  if($type == 'ajax') {
    $output = t('Hello World!');
    $command = array();
    $commands[] = ajax_command_append('#sayinghello', $output);
    $page = array('#type' => 'ajax', '#ajax_command' => $commands);
    ajax_deliver($page);
  }
  else{
    return t("Hello world in new page.");
  }
}

I did it :
The problem was in my callback function :

function custom_ajaxcallback($type = 'ajax') {
  if($type == 'ajax') {
    $output = t('Hello World!');
    $command = array();
    $commands[] = ajax_command_append('#sayinghello', $output);
    $page = array('#type' => 'ajax', '#commands' => $commands); --> In this line
    ajax_deliver($page);
  }
  else{
    return t("Hello world in new page.");
  }
}


How to change the date of rewarded User Points? When users publish a node on my website, they are rewarded some User Points with Rules. So when one publishes a new node on 25th June 2016, the User Points are stored with the exact same date.

As an administrator, I published some nodes where I changed the author and the date (say, 25th June 2012) in Authoring information in the node's form. However, after publishing, the User Points were of course stored as granted on 25th June 2016 instead of 25th June 2012.

Is it possible to change the date of a User Points transaction and replace it with the same time on which the linked entity (i.e. the node) was created? That is, in this case, the date of the transaction should be 25th June 2012.

I am aware that one can manually change the data in the database, but I suppose (and hope!) that there is a more efficient way.

Have a look at the User Points Contributed modules as a possible alternative. I.e. its submodule userpoints_retroactive. Excerpt from that project page:

  Award users points for their nodes, comments and votes that they have created so far, before userpoints was enabled on the site.

Comment nr 9 of issue nr 1187616 contains a patch with these enhancements:

Ported the module to Drupal 7.
Added support for retroactive revisions.
Made provisions to store the timestamp of original node and revision.

So instead of trying to change the dates of the User Points transactions, I'd delete the transactions you already have, and try to recreate these transactions using this patch.

PS: there is also Berdir's Api documentation about this submodule ... (maybe that helps somehow).


Hide page title if the image field has a value I have a image field (field_image) on my content type. I want to show the image below the header with the node title inside. I am successfully doing that in page.html.twig.

{% if node.field_image %}

{{ node.label }}

{% endif %}

However, the page title is also showing up in the page title block inside of the Header region. I'm trying to find a way to hide the second page title, on the full node view, if the field_image field has a value.

How can I achieve this?

This method works for me. (Thanks to kim.kennof on Slack for the assistance.)

In my THEME.theme file:

function THEME_preprocess_page_title(&$variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    if ($node instanceof \Drupal\node\Entity\Node) {
      $variables['node'] = $node;
    }
  }
}

Then in page-title.html.twig:

{% if node.field_image is empty %}
  {% if title %}
    <h1{{ title_attributes.addClass('page-header') }}>{{ title }}</h1>
  {% endif %}
{% endif %}


How to use composer for module dependency? I installed Drupal 8, and for the Panels module, I had to install the following other modules manually:

Page Manager
Layout
Chaos tools suite

Can we use composer to install modules with their dependencies?

See this composer template for Drupal project for an example of how this works. Usage:

composer create-project drupal-composer/drupal-project:8.x-dev some-dir --stability dev --no-interaction

With composer require ... you can download new dependencies to your installation.

cd some-dir
composer require drupal/devel:~1.0


How can I customize the message after register? How can I change, or customize, the message shown to the user after registration in Drupal 7?

  Further instructions have been sent to your e-mail address.

I tried the following code, but it didn't work for me.

function mymodule_message_alter(&$messages) {
  switch($messages->messages['status'][0]) {
    case 'Further instructions have been sent to your e-mail address.':
      $messages->messages['status'][0] = t('Your reset password instructions have been sent to your e-mail address. Please check your email and follow the instructions</p>');
    break;
  }

  // Disabling / Suppress all messages on a page and only display one Message
  if(arg(0) =='your-custom-page') {
    if($messages->messages['error']) {
      unset($messages->messages['error']);
      $messages->messages['error'][0] = t('This is my custom message to replace 10 system messages :) ');
    }
  }
  return $messages;
}

It might be overkill for a single message but the String Overrides module would work.

It includes a UI for quickly adding string replacements for anything that is passed through the t() function, which includes the message that you're trying to replace.


How to include a view in a specific region defined in a custom layout? I defined a set of views that I would like to include in specific regions ordered in a particular way through a custom layout. However, the block menu does not allow me to select these regions. All I can do is to give an order (1, 2, 3, etc.) to these views, which does not solve my problem because I need the views' outcomes to show up in these specific areas of the page.

I've looked up in many places but I couldn't find any answer to that question. Someone could give me a hint?

Thanks a lot!
Igor

You can embed views anywhere with php with views_embed_view(). Please refer https://api.drupal.org/api/views/views.module/function/views_embed_view/7


How to add tri-state checkboxes to form created with Form API? I want classical tr-state checkboxes, like the ones on the picture below:

Checked would mean "true for node and all it's children", intermediate "true for some children, leave it as it was" and uncecked "false for all children". Desired values (but that's not a must) are:

checked - TRUE
unchecked - FALSE
intermediate - NULL

Is there a module to provide control like this? Or to provide intermediate value for regular checkboxes?

I need it for Drupal 7, but I'll gladly welcome answers for 6 and 8 too.

From what I understand, the indeterminate property of a checkbox is purely a visual thing, and also cannot be set with HTML, which in turn means that you won't be able to use the FormAPI or create an indeterminate element without JavaScript.

Chris Coyier sets out some example situations though in this blog post, but an important quote is below (in case the post goes down).

  Here are some things to know about indeterminate checkboxes:

  You can't make a checkbox indeterminate through HTML. There is no
  indeterminate attribute. It is a property of checkboxes though, which
  you can change via JavaScript.

I should imagine you could probably use Drupal.settings to your advantage here though, and run the check server-side for "true for some children", and pass an array of ID's through to Drupal.settings. Following that run something like the following in a Drupal behaviour:

 // This is an array of IDs
 trueForSomeChildren = Drupal.settings.myModule.trueForSomeChildren;

 $(trueForSomeChildrenjoin(', ')).attr("indeterminate", true);

Howeverm I don't think there's an already-built module to do what you want. There is a patch here for the FacetAPI where they allow for indeterminate, but it kind of follows this example.


Send newsletter action - after saving simplenews node I would like to do the same thing that described here: http://drupal.org/node/1427246

So, I use drupal 7, simplenews, schedule, and import modules.

I want to import my simplenews nodes, and they have scheduled date and time to publish...

But the problem for me is there is no way to set "send newsletter" status for the newsletter nodes automatically. I should click on each and every node to approve it to send.

On the link above there is a solution:

  "Create a rule that is triggered when a node is inserted (update makes
  no sense as you can't resend a newsletter, add a condition on the node
  content type and then execute the Send newsletter action."

My question: how can I activate the "Send newsletter action". It is not appear on the list of available actions.

You need to enable the simplenews_rules module which comes packaged with simplenews - this has the action for sending a newsletter defined:

'simplenews_rules_action_send' => array(
  'label' => t('Send newsletter'),
  'group' => t('Simplenews'),
  'parameter' => array(
    'node' => array(
      'type' => 'node',
      'label' => t('The newsletter node to be sent.'),
      'description' => t('The newsletter node that should be sent.'),
    )
  )
),


Can you render a custom block in a view without adding it to the admin blocks page? I made a custom block in my custom module.  I now want to show that block in the "No results" area of a view, but I can't get it to render (I don't see any error message, and I don't see any output).
Here is the block definition:
/**
 * Provides an 'New User' Block.
 *
 * @Block(
 *   id = "newuser_block",
 *   admin_label = @Translation("New user block"),
 *   category = @Translation("MYMODULE"),
 * )
 *

In my view, in the "No results" section, I added Rendered entity - Block, and set the Block ID to newuser_block.
However, the block does not get rendered.
This is because I did not add the block on the block admin page at /admin/structure/block. When I add the block on the admin page and use the admin page block ID (not the block machine name), the block is rendered correctly.
However, I don't want to add the block to the admin page because I only need this block in a few places on my site, so I was using Layout Builder to inject the block where necessary.
So, is there a way to inject a block by machine name (instead of by the ID used on the block admin page) in Views?

The only purpose of a block plugin is to be placed as a block. It's not an entity. The placed block instance can become an entity of its own but also be part of a layout section.
Since the block is your own custom code you don't need any of the workarounds discussed and linked. It would make more sense to refactor the code and expose it as block plugin to be placed on the page and at the same time as area plugin to be placed in a View.
For sharing the custom code between both plugins you can use classic OOP, or the in Drupal very common traits and services. The service has the advantage that it is more flexible and you can not only share code but also data, for example to cache the result if it is expensive to calculate and used in multiple places.


drupal_add_js only once I have a field which is used in a nodeblock, and only appears on a few select pages. This however will vary throughout the lifetime of the website so I've been looking for a way to insert the Javascript this field requires only when it's present. Additionally, the field can appear more than once on any given page.

Looking at drupal_add_js, I can't see that it provides a way to only include JS once. Using this I was hoping that I could just call it in the field--field-name.tpl.php file for that field but as it occurs multiple times, the JS is included more than once.

I've looked at the module JS Injector, but that's just page specific and just calls the aforementioned function. This wouldn't help me because every time a new block is added somewhere, the list of pages including the JS would also need to be updated.

Is there a way I can include a JS file just once in Drupal?

It depends what type of javascript you are adding.

drupal_add_js will only add files once, no matter how often it's called ;
Settings would overwrite previous values, so it's not a major problem ;
Inline code would indeed get added multiple times.

Given that your script needs including only once no matter how often the field is present, I assume you are not generating it's code on the fly - so putting it in a file would be an option.

Otherwise, as suggested by Clive, you could have your own wrapper around drupal_add_js that ensures a given inline js is only added once by using a static variable.


SMTP Authentication Support + Unable to send e-mail I'm working on my localhost with a drupal project. I'd like to be able to send emails so I installed the SMTP Authentication Support module. Now I'm configuring it to send it with my gmail address but the test mail can't be send. I always get this error:

Unable to send e-mail. Contact the site administrator if the problem persists.

My Settings:

SMTP Server: smtp.gmail.com
SMTP Port: 465
Use encrypted protocol: no
Username: myusername@gmail.com (yes, this is correct in my settings)
Password: mypassword (yes, this is correct in my settings)
E-mail from address: myusername@gmail.com
E-mail from name: my username
E-mail address to send a test e-mail to: myotheremailaddress@hotmail.com

When I check the Enable Debugging checkbox I get this after trying:

SMTP -> FROM SERVER:
SMTP -> FROM SERVER:
SMTP -> ERROR: EHLO not accepted from server:
SMTP -> FROM SERVER:
SMTP -> ERROR: HELO not accepted from server:
SMTP -> ERROR: AUTH not accepted from server:
SMTP -> NOTICE: EOF caught while checking if connectedSMTP Error: Could not authenticate.

Am I doing something wrong?

I've also tried it with PHPMailer module with the same settings, same result ..

Looks like Gmail needs SSL encryption, so I had to select that in the list of encryption, my bad!


Split an array of ids and save it as individual rows in table I managed to get all ids from a table using query in drupal. I got the array of ids. I'm struggling to insert all the ids in another table as individual rows. As Im new to the drupal concepts,its very difficult for me to figure it out. Any help is appreciable.:)

You can use db_insert in your module OR drupal_write_record

E.g: drupal 7 code

 //Assuming your array is like
 /*
   $ids = array(1,2,3,4,5,6,....);
 */

  // Traversing ids by using foreach loop
  foreach($ids_array as $key=>$value){
       $custom_table_data = array(
            'id'=>$value,// id value
            'column1'=>'..'
        );

       // INSERT INTO {table_name} (field_1, field_2, ...) VALUES ('ABC', '123', ....)
        $nid = db_insert('table_name') // Table name no longer needs {}
        ->fields($custom_table_data)
        ->execute();

        // OR using drupal_write_record...
        drupal_write_record('table_name', $custom_table_data);
  }


Make field content as exposed filter dropdown I have a field in my node like brand, where in admin enters the brand name and creates the node. I want to make a exposed filter out of this as a dropdown with all the data entered by the admin. How do i do it ?

your question isn't 100% clear but it sounds like you want to display the nodes in a view and want to filter them with an exposed "brand" dropdown?
I also assume your "brand" field is a term reference to a vocabulary.

Create a view for the nodes and add a filter for "Content: Has taxonomy term" and select your "brand" vocabulary, "dropdown" as the filter type and "expose this filter".


How can I override the search result page title dynamically? In my Drupal 8 site, I am using the default search page. If I enter a keyword, for example article, the search result will be listed under Search result.
I want to change that to Search result for Article (keyword).
How can I achieve this?

Here comes an example snippet on how to override the page title by URL query:

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_page_title(&$variables) {

  $current_path = \Drupal::request()->getpathInfo();
  if ($current_path == '/search/node') {
    if (\Drupal::request()->query->has('keys')) {

      // Get the searched string.
      $keywords = \Drupal::request()->query->get('keys');

      // As of https://drupal.stackexchange.com/a/232304/15055 we probably
      // need to ensure the cache gets busted.
      $variables['#cache']['contexts'][] = 'url.query_args:keys';

      // Set the new title.
      $new_title = new \Drupal\Core\StringTranslation\TranslatableMarkup('Search result for Article (@keywords)', ['@keywords' => $keywords]);
      $variables['title'] = $new_title;
    }
  }
}


How to render a block in php for a special node id I would like to render a block from only one node on all node pages. But all the code I found to render blocks never takes the nid as an input. Is there a possibility that I can trick the block renderer into thinking it is on a different page?

If it is of any help: In my case I want to render the block for Opening hours from one node id on all pages. So I do not have to add the same opening hours for every node.

Add this to your theme's template.php file:

function THEME_block_view_alter(&$data, $block) {
  if ($block->module == 'opening_hours' && $block->delta == 'week') {
    $node_fixed = node_load(77); // swap out 77 for your node's id
    if ($node_fixed) {
      $data['content']['#node'] = $node_fixed;
    }
  }
}


How to use Rules to flag a node on behalf of ALL users who had previously flagged it with a different flag? Here's what I'm trying to do:

I have a content type of Question.
Questions have a field that identifies their status as "asked" or "answered".
Questions marked "asked" can be flagged (using Flag Module) as "follow" by users.
When an admin changes the status field of a Question from "asked" to "answered" I would like to flag the Question with an additional flag called "archive" for all the users who "follow" the question.

This is how I set up the rule:

1. Events:
After updating existing content

2. Conditions:
Entity has field (Parameter: Entity: [node], Field: field_question_status)
AND
Data Comparison (Parameter: Data to compare: [node:field-question-status], Data value: Answered

3. Actions:
Fetch users who have flagged a content (Parameter: Flag: Follow, Content: [node]
Provides variables: Users who flagged (users)
LOOP
(Parameter: List: [users]
List item: Current list item (list_item))
ACTION-IN-LOOP
Flag a Content (Parameter: Flag: Archive, Content: [node], User on whose behalf to flag: [users:0], Skip permission check: true)

Here's my problem:

The rule seems to be working for only one user at a time. So if 3 users have "followed" a Question and it is switched to "answered" status only one of the users will have the Question flagged as "archive". I found I can specify an individual user in the ACTION-IN-LOOP (action nested in the loop) by changing the value of "User on whose behalf to flag: [users:0]". If I switch the value to users:1 or users:2 then the rule works for those individual users but not all. The only other option I can think of is to try [users] without any additional chained value, but this gives the error "The data type of the configured argument does not match the parameter's flagging_user requirement." How do I get a rule to flag the node (with "archive) on behalf of ALL users who had previously followed it?

You need to flag on behalf of the user that the loop is operating with each iteration. Either that or add a numerical variable that you increment each loop and fetch that index from the list of users for the behalf of which to flag


How to do an EntityQuery on a custom User field? I'm having trouble figuring out how to use the EntityQuery on custom field values. As an example I have a custom field under the User bundle that stores the country in which the user lives. There are three options: US, Canada and Mexico. I'd like to use the EntityQuery to directly query the 'field_country' to get a count of how many live in one country and get their uids. Here is an export from the database for this field:

The closest I've gotten is the code snippet below. This however is not working and I'm not sure where to go from here.

$results = \Drupal::entityQuery('user')
      ->condition('field_country', 'Canada')
      ->execute();

Does anybody know? Does the entityquery give me the ability to look specific columns in a field? Thanks!

P.S. I know I could do this with a database query but I'd prefer to do it the Drupal way.

I think you might be missing a line:

$ids = \Drupal::entityQuery('user')
  ->condition('field_country', 'Canada')
  ->execute(); // This returns the user ids

// Load the users
$users = User::loadMultiple($ids);
foreach ($users as $uid => $user) {
    // $user contains the $user entity
}

More examples are located on the docs page.


.bash_profile has to be resourced every time I installed Drush 8.0.0 for Drupal 8 on Linux Mint 17.1 via Composer.

I added Composer's directory to .bash_profile.

export PATH="$HOME/.composer/vendor/bin:$PATH"

The problem is that every time I want to run Drush now, I have to re-source .bash_profile with source ~/.bash_profile.

Otherwise, I get an error saying it is not installed.

  The program 'drush' is currently not installed. You can install it by typing: sudo apt-get install drush

How can I keep it sourced?

You need to put these commands in your ~/.bashrc file, which is sourced every time a new shell is started.

You might also want to try the new drush init command, which should do this setup for you.  Be sure that you are using Drush 8.0.1 or later.


Detect browser in preprocess function My goal is to render a warning message to IE 11 users, prompting them to use a modern browser.

I'm a bit of a noob, but from what I understand, it's possible to detect a user's browser using a preprocess function. I found this function online, which looks like it does what I need it to do, but I'm getting a "The website encountered an unexpected error. Please try again later." error when I add it to my THEMENAME.theme file.

function THEMENAME_preprocess(&$variables, $hook){
  if (get_browser_name(htmlentities($_SERVER['HTTP_USER_AGENT'], ENT_QUOTES, 'UTF-8')) == 'Internet Explorer'){
       $variables['browserIs'] = 'IE';
   }
   else{
       $variables['browserIs'] = 'OTHERS';
   }
 }

Any ideas on how I can accomplish what I need?

The function would be get_browser. But you should be using Javascript to detect this instead of PHP.

There are a variety of ways it would fail/be incorrect from the PHP layer, caching, spoofing, etc. Once it gets cached, it would show up for the next person regardless of what browser they are using.

Plenty of JS libs out there can detect it as close as possible, but there is also a module ready to roll here as well that will just solve this for you more than likely, one such module being Browser Detect. There are a few modules for this actually, try them out and see what one suits you best.


Drush can't find php I am on a shared server and someone else has installed Drush previously. But as of now Drush does not work and throws the following error.

[root@vps1]# drush
/root/.composer/vendor/bin/drush: line 47: which: command not found
ERROR: can't find php.

The last thing I can remember was updating PHP (mod_php) to 5.4.36 several days ago. It worked on 5.4.34, but PHP was recompiled during the update. Is this related? What do I need to do to tell drush about this 'new' php?

which: command not found

I don't really use Drush,  but that looks like it's dying when it uses the "which" command to locate PHP...  Drush is falsely reporting that PHP can't be found,  but it's because the command it uses to look for it ("which") is not available.


Display a flag link in views based on whether the node has an associated taxonomy term All of my nodes of a certain content type are given a category by assigning a taxonomy term. I would only like to add the flag, "My Fruits" if the content has the term "Fruit" assigned to it.

So far I've attempted using a views PHP field to add the flag:

This works to simply print the flag:

<?php
print flag_create_link("basket_01_t01_fruit", $row->nid);
?>

But this, I'm not able to get working:

<?php
if ($row->field_item_produce_type == '3') {
print flag_create_link("basket_01_t01_fruit", $row->nid);
}
?>

Any ideas would be appreciated.

You could achieve this easily using views without using views php field. More specifically you can create a view of content with an EVA (entity views attach) field display where you will add the flag link field and attach it to the nodes of that content type. Just make sure to:

Add a contextual filter of Content:Nid
Add a relationship of "Content:Taxonomy terms on node"
Also add a "Flags: Node flag" relationship (uncheck the include flagged content only checkbox)
Add a filter "Content type:...your content type which nodes will have the flag link
Add a filter "Taxonomy term: Term ID" that will equal to the tid of the "fruit" term.

After that you can easily choose how to display this eva field on your nodes using Display suite.


How do I add a field in the toolbar? How do I add a custom field in the toolbar?

The examples module kinda does this:

it's not a drop down, but lists the links under. Take a look at // Create the examples toolbar render array. in examples.module to see how they do it.

Now, I don't know if you can put an actual field in the toolbar with PHP code. The only thing that I can think of is to use CSS. I tested this and it worked.

.field-in-question { position: fixed; top: 10px; z-index: 999; }


Page manager, Panels and theme suggestions Page manager and theme suggestions

I have two types of layout

custom_2col_brick
custom_1col_landing

and I need to render the page according to the selected layout.
basically, I needed two page template for each layout. something like the following:

page__custom_2col_brick.html.twig
page__custom_1col_landing.html.twig

Is there a way to do this?

In Drupal 7 I could do it as follows, but panels_get_current_page_display is not working in Drupal 8

/**
 * Implements hook_preprocess_page().
 *
 * @see page.tpl.php
 */

function THEME_preprocess_page(&$variables) {

    if (module_exists('ctools') && module_exists('page_manager')) {
        $display = panels_get_current_page_display();
        $layout = (isset($display->layout)) ? $display->layout : false;

        /* layout e.g column_one_fluid, column_three_fluid etc. */
        $fluid   =  $layout ? preg_match("/\s*.+_fluid$/", $layout) : false;

        /* layout e.g column_one_landing, column_three_landing_fluid etc. */
        $landing =  $layout ? preg_match("/\s*.+_landing$|\s*.+_landing_fluid$/", $layout) : false;

        $variables['page_fluid'] = ($fluid) ? true : false;
        $variables['page_landing'] = ($landing) ? true : false;

        if($fluid) {
             $variables['theme_hook_suggestions'][] = 'page__fluid';
        }
        if($landing) {
            $variables['theme_hook_suggestions'][] = 'page__landing';
        }

    }

If you don't already have one create a yourtheme.layouts.yml file in your theme folder. There you will define the regions, preview icons, and labels.

custom_2col_brick:
  label: Two Column Brick
  category: My Custom Layouts
  template: layouts/custom_2col_brick
  icon: layouts/custom_2col_brick.png
  regions:
    left:
      label: Left
    right:
      label: Right
    footer:
      label: Footer
custom_1col_landing:
  label: One Column Landing
  category: My Custom Layouts
  template: layouts/custom_1col_landing
  icon: layouts/custom_1col_landing.png
  regions:
    main:
      label: Main Region
    footer:
      label: Footer

Now you can create your page__custom_2col_brick.html.twig and page__custom_1col_landing.html.twig files in your layouts folder. Inside there you can define your template. For example custom_1col_landing.html.twig could contain

        {{ content.main }}

        {{ content.footer }}

Once finished you should have the following files. (The preview icons are optional)

/yourtheme/yourtheme.layouts.yml
/yourtheme/layouts/custom_2col_brick.html.twig
/yourtheme/layouts/custom_1col_landing.twig


How to display the average of the votes of a rating field from a form made with webform (D8)? I've made a rating form using the webform module.
I'm looking for a way to display the average result of the votes on the node.
Any suggestions?

Check out the Webform Analysis module.

  This module is used to obtain statistics on the results of form
  submissions.


How to create a view that lists one post per user For a blog homepage I am trying to output a view that lists a single post for each user on the site. It needs to be sorted by date, so the latest post is shown at the top.

I'm trying the 'view inside a view' method here http://groups.drupal.org/node/11746 but thinking there must be a better solution out there.

The solution was to use Rules and Views bulk operations (VBO) to change the 'promoted to front page' property of that users blog posts when they submit a new post. The triggered rule simply removes 'promoted to front page' from all their posts and then adds it back to the newly submitted node. Thus, each user will only have a single blog post with this property, which makes the blog homepage easy as you simply create a view sorted by date and filtered with the 'promoted to front page' property. Johan Falk has done some excellent tutorials on using rules and VBO. Well worth a watch.


How do I print breadcrumbs on page.html.twig? How do I print breadcrumbs on page.html.twig?

I tried {{ breadcrumb }} but it's not working.

The breadcrumbs are now a block. You have to go to the block layout and put them into a region. If you want {{ page.breadcrumb }} to work, you have to put them into the region breadcrumb.

This is the same for site branding and title, they all have moved into blocks.


How do I remove frontpage content block? I am trying to remove the main page content page. I made a views slider (block) which I then displayed on the frontpage. However, I am finding it difficult to remove the mainpage content block. I am using drupal 7 and the zen subtheme.

You cannot remove the content part of a page as it is not a block. The content is suppose to be your main content that always shows and blocks are things that can be conditionally shown around your content.

You can create a page display for your view, then change the front page of your Drupal site to point to your views page display (D7: admin/config/system/site-information, D6: admin/settings/site-information).


not able to display the real name of the users First of all, I am not a techie and have picked the codes mentioned below from various sources. I have added two new fields to the user profile - 'firstname' and 'surname'. I am using a custom theme and on one of the places (on a node), I need to display the real name (making some code changes) instead of the username.

I am replacing the existing code -

<?php print $node->name ?>

With this -

<?php
     $profile = user_load($node->uid);
     $profile = user_view($profile);
     $firstname = render($profile['field_firstname']);
     $surname = render($profile['field_surname']);
     print $firstname.' '.$surname; ?>

However, a strange thing is happening. I am able to print the surname correctly but the firstname is blank every time, even when I tried to print only the firstname (or the surname). Why is it that the firstname is not getting picked? What changes should I make?

Did you try real name module before write your own code?

I did not use 6.x version, but i guess it will be more flexible than your solution.


How to disable htmlspecialchars in custom module form table? I'm making a table form

$form['table'] = [
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $this->getOutput(),
  '#empty' => t('No vehicles found'),
];

In getOutput() I have 'vehicleName' =>  "vehicleId . "\">"  . $vehicle->vehicleName . "", for one of the fields. And it doesn't print out as normal html. It goes through htmlspecialchars() and I don't have clickable link at the end. How can I disable this?

You can use FormattableMarkup

Here's a simple example to get you started

use Drupal\Component\Render\FormattableMarkup; // place this at top of file

$options = [
  1 => ['foo' => 'Foo'],
  2 => ['foo' => 'Bar'],
  3 => ['foo' => new FormattableMarkup('I am a link', [])],
];

$header = [
  'foo' => t('Foo bar')
];

$form['table'] = [
  '#type' => 'tableselect',
  '#title' => t('Foo bar table'),
  '#header' => $header,
  '#options' => $options,
  '#empty' => t('No foos found.'),
];

So in your case $this->getOutput() may return something like (this is untested):

['vehicleName' =>  new FormattableMarkup(
  '@name',
  ['@id' => $vehicle->vehicleId, '@name' => $vehicle->vehicleName]
)]


How can I schedule adding a new field collection item for all users? My users have a field collection, called 'Score', with two fields: 'Date' and 'Points'. I'd like to add a new field collection item for all users at the end of the day, with the current date in 'Date' and their current userpoints in 'Points'.

I thought about using a scheduled rule, but I don't know how I can select something like 'all users'. Is this possible with Rules or is there another way to achieve this?

This question is part of How to create a line graph of the total user points on a profile page?.

I'm not sure about rules but you could do that in a custom module with a little code:

$uids = db_query("SELECT uid FROM {users} WHERE status=1")->fetchCol();
$accounts = user_load_multiple($uids);
foreach($accounts as $account) {
    $edit['my_field'][LANGUAGE_NONE]['0']['value'] = 'my new value';
    user_save($account, $edit);
}


How do I return JSON data compatible with the Boost module? In a custom module a, I return a JSON string that needs to be compatible with the Boost module.

My first try was using the following code:

if ((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'XMLHttpRequest' == $_SERVER['HTTP_X_REQUESTED_WITH']) || strpos($_SERVER['REQUEST_URI'], '?json') !== FALSE) {
  header('Cache-Control: no-cache, must-revalidate');
  header('Content-type: application/json', true);
  $json = loadData();
  die(json_encode($json));
}

This is obviously that this output won't be cached. Than I replaced the line with die() with the following one:

return drupal_json_output(($json));

This works, but it is not cached. I enabled the JSON output in Boost, but nothing happens.

What should I try?

Removing the two header lines does not change anything. The function drupal_json_output adds the Content-Type: application/json. But I belive that boost only accepts text/javascript. Also if I override the Content-Type again nothing will be cached.

Why do you need to cache JSON output? Anyhow, try removing header('Cache-Control: no-cache, must-revalidate'); and see what happens.


add custom data attributes to block from block configuration page Here is what I would like to accomplish:
 1. Add data attributes to block (for example: data-key="value")
 2. Nice to have: add a text area to block config page where i can enter data attribute key-value pairs (one per line) and have them added to the block.

Any guidance is greatly appreciated

You will need to create a custom block using hook block info, hook block view and hook block configure. That last hook will let you as a form render array (see drupal form api).

The custom block system in drupal 7 isn't very good. If you need anything but the simplest HTML code then you should create your own blocks using the above hooks.


How to change the default term path "taxonomy/term/[tid]" Am using drupal 7 for my project.

Here am facing for custom url change.

My website url is www.example.com/plans/1. Above url need to change as www.example.com/plan-name.

Pls suggest to me to fix the issue.

Please go Configuration->search and metadata -> url aliases -> pattern.

Check over to the Taxonomy Term Path. If you have created the plan as Taxonomy.

Go to the Pattern for the Taxonomy plan and then create the URL path of the plan

If you want to display the Id in URL,give plan/[term:tid] or taxonomy name give it as plan/[term:name].


Migrating and developing content types I have partially defined a complex content type on a remote site. It's not finished, by no means. Now, I want to migrate this content type to localhost so to continue my development locally. An obvious choice for exporting/importing data is Features. But - if I export the content type definition as a feature, will I be able then to develop it further on localhost? If not, what would be the right way to go?

You will have no problem if you have the same field types installed on the localhost. For example If you are using the email field in your production site, it should be installed also in the localhost.

Assuming your are using Drupal 7, you have three choices:

Features
Bundle copy

  Bundle copy is a replacement for the Content copy module which lives
  in the CCK project for Drupal 6.

Field tools(currently alpha)


How to load a node on a mini-panel I want to make a mini panel loaded with the fields of the "Node being viewed".
But I don't know how to make this happen. Any suggestions?

This requires that a node context get passed into the mini panel for it to know what node to pull the data from. Unfortunately there is no way to pass this context using blocks.

You can use page manager to create a node view page which has the correct node context and put the mini panel there.

You can create a view that has a default argument set to get the node id from the URL. Then create a pane display on this view. You can add this view to the mini panel and it will get the node info correctly so you can use blocks.


Setting multisite in WAMP I have created folder structure like below:

Main Drupal: www_d8multisite_com

Subsite1: www_d8multisite_com/sites/default/ms1
Subsite2: www_d8multisite_com/sites/default/ms2

And put the sites.php inside

www_d8multisite_com/sites/sites.php

and defined my multisite like below:

$sites['www.d8ms1.com'] = 'ms1';
$sites['www.d8ms1.com'] = 'ms2';

And put the settings.php in both subsite folders like below:

Subsite1: www_d8multisite_com/sites/default/ms1/settings.php
Subsite2: www_d8multisite_com/sites/default/ms2/settings.php

Then I setup my virtual host like below:

<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host2.example.com
    DocumentRoot "H:/wamp/www/www_d8multisite_com"
    ServerName www.d8ms1.com
    ServerAlias www.d8ms1.com
    ErrorLog "logs/www.d8ms1.com.error.log"
    CustomLog "logs/www.d8ms1.com-access.log" common
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host2.example.com
    DocumentRoot "H:/wamp/www/www_d8multisite_com"
    ServerName www.d8ms2.com
    ServerAlias www.d8ms2.com
    ErrorLog "logs/www.d8ms2.com.error.log"
    CustomLog "logs/www.d8ms2.com-access.log" common
</VirtualHost>

Still my multiste is not working. If I'm trying to access any of the subsites(www.d8ms1.com or www.d8ms2.com) it only pointing to base site. I mean site is still loading from base www_d8multisite_com. not from sub folders.

Am I doing something wrong in the configuration? or I missed any step?

I have never really used multi site much, but I have read the documentation multiple times nevertheless.

It always was my understanding that the default folder was reserved for the default site, and that all other folders should be placed next to it, not inside of it.

Next to that, the documentation implies that your folder name should match a certain pattern, based on the site url.

Instead of using www_d8multisite_com/sites/default/ms1 I'd try using www_d8multisite_com/sites/d8ms1.com instead.


How to get rendered content properties from an entity reference in Twig I'm using the Stock Photo Search module, for particular image fields, and it has its own field type with interesting properties.

As far as I can tell, the only way to access the URI of the image is content.field_stock_photo[0]['#uri']. There is no node.field_stock_photo.0.entity.uri.value or similar. The only way to access the URI is through the rendered entity.

The problem I'm running into is when using a reference to another node that has the stock_photo_search field, I have no way to access this rendered entity from a reference.  node.reference.0.entity.field_stock_photo.value doesn't do it, and as far as I can tell node.reference.0.content.field_stock_photo doesn't work.

How do I go about getting properties from a rendered entity of a reference in Twig?

In PHP you could force to build the render array of the field of a referenced entity early:

$build = $node->reference->entity->field_stock_photo->view();

And then look for '#uri' in the build array.


Is there a property that is set by the field API once fields have been attached to an entity? Is there a property that is set by the field API once fields have been attached to an entity?

For example

$entity->fields_attached = TRUE

I have been unable to find any information on this, I am looking for a quick and easy way to know if fields have been attached to my own custom entities. If field API does not do something like I have suggested in the question I will handle it myself but I wanted to double check with you fine folks...

If not, I will make a suggestion for this for the Entity API in contrib whenever it attaches fields.

Many thanks in advance :)

No, there is no property on the entity, but you can use field_info_instances() to check on which bundles the field is in use.


Views: Filter if Value of a field equals logged in user display name? How to do I create a filter on my view that filters based on the value of one field being equal to the name of the currently logged in user? The field is static.

You can use contextual filter as suggested by @Smalution. Go to your view click on add Contextual filter on right side of it, then select the field you want to use as a filter and do as shown in below image:

To use with name try this:


How to keep URL parameters on subsequent pages after a form is submitted? I'm sending a referral form out to my email database and I've got it set up so that their email addresses get passed through and appended to the form URL like this:

http://www.holbrooktravel.com/referral-form?emailid=sarah@holbrooktravel.com

I've got a hidden field in the form that collects the 'emailid' value and stores it with the responses so they can be matched up with our database.

That's working well, but once someone submits their form they're sent to a thank you page (http://www.holbrooktravel.com/referral-form/thank-you) where they can click a button to go back to the form and refer someone else.

I can't figure out how to keep their 'emailid' value on the 2nd referral so those submissions can be matched up as well. If I'm on the right line of thinking then I need to somehow keep the URL parameters on both the thank you page and the link sending them back to the referral form.

Any suggestions would be very much appreciated!

If you're able, and willing, to review/rework the current implementation you have for your webform submissions and the related "Thank you" page, you should consider getting the Rules module involved, e.g. to have the Rules module react to Rules event "After submitting a webform".
By doing so, you could then also use the Rules URL Argument module, which you can use to make the value of the URL argument available as new variable to Rules. Here is a quote about it (from its project page):

... provides two rules conditions based on URL arguments:

check if a URL argument is present.
compare the value of an URL argument.

It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.
For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.


Where did drush language-add disappear? I was using it for a long time in the install script and today it stopped working and I don't remember changing anything related.

  The drush command 'language-add' could not be found.

Was it part of l10n_update (I have it enabled), drush itself or something else?

This https://drupal.org/project/drush_language is not what I'm looking for. It doesn't work and I've never seen it before.

The problem is caused by not installing drush_language in the correct directory.
If you stil have the problem:

First remove anything related to drush_language:

Go to your drupal folder and do drush pmu drush_language
Go to /drupal/sites/all/modules and delete the directory drush_language, if it's there.
check your system for a global drush_language: e.g. do updatedb & locate drush_language. Then delete any folders called drush_language.
Go back to your drupal root folder an do: drush dl drush_language --destination=./sites/all/modules/


Flip Boolean Value in Field I have a product with a field that's a boolean value "Contains Gluten" which stores a "1" for yes and a "0" for no, this is stored in the database as field_contains_gluten_value.

The client now wants it to say "Gluten Free" instead.

Rather than change all of my views and product displays to negate, I figure it would be easier to just flip the value in the database.

I am using feeds to import the products from a csv, but the client has edited products now and changed other fields, so I don't want to change it in excel and import over the top for fear of losing his changes.

In the database how do I change all the "0" values to "1" and vice versa? I'm aware this might not qualify as a Drupal question and might be better on stack overflow, but if there is a Drupal solution you are aware of then I'm all ears!

The SQL would be something like:

UPDATE [field table] SET [field column name]=1 WHERE [field column name]=0


Provide additional Status option for user_profile_form I am writing the below code

     function mymodule_form_alter(&$form,&$form_state,$form_id){
      if($form_id == 'user_register_form' && $form_id == 'user_profile_form'){
        $form['account']['status']['#options'] = array(0 =>'Blocked', 1=>'Active', 2 => 'Closed', 3 => 'Ractive');
        }
     }

I am able to see the options at user register form but not in user profile form.
How to add other option on user profile edit.

You have implemented hook_form_FORM_ID_alter(), which only fires for a single form (user_register_form in this case).

If you want to use multiple forms in a single function, you need hook_form_alter():

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form' || $form_id == 'user_profile_form') {
  ...
}


Action when a comment has been replied to I have a unique case where we need to do something, namely a behavior where a user Comments on a node, and when a new comment is made in response to him, we need to "alert" the user in a variety of ways. Right now, lets say we need to send him an email.

I'm not sure of the best approach to implement this logic, but it looks like it may be possible to extend the Rules module to do so. What would this logic look like? Are there other approaches that can be used here?

I've got something similar in setting up a forum, where all posts on a topic are really just comments. We've set it up to allow people to "subscribe" to the topic via the Flag module and then have a Rule set up to notify all subscribers after a new comment is added. Here's the Rule (from /admin/config/workflow/rules )

And here's how it looks when you click "Edit" in the screen above:

So basically, I've set up an event for a comment being added to a forum topic, then under actions, fetch all the users who have flagged that node and loop through, sending them an email (which can be customized with tokens based on the newly added comment). You can automatically flag a user to a node when they create it or comment on it.


How to print anything in a twig template file In drupal 7 we were able to resort to simple php functions in tpl.php files to load anything we wanted. Entities, blocks, view etc. This was really powerful for making really customisable blocks. In D7 we can use this php:

$block = block_load('views', 'block_name');
$output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block   ))));

When it comes to D8 I have read things about the getParameter but i'm coming up short on how to do it in a twig tpl.

For example, in a custom field in D8 I can get the node by using:

$node = \Drupal::routeMatch()->getParameter('node');

But how do I do this for a view on a page? And how would I do this in a twig.tpl in which you cannot write php?

I'm interested to see how people are tackling this in D8 or if I have the complete wrong method here.

better practice is to do that in preprocess functions !

so, fe. in preprocess page, you can access the node (if existing) via the $variables array and so on ..., then you add your own variables for the twig template, like:

$variables['my_fancy_block'] = \Drupal::service('renderer')->renderRoot($whatever);

and access this like:

{{ my_fancy_block }}


How can I add an extra button & submit handler to an exposed view form? I would like to add a second button to an exposed view form.

I am able to get the button to display, but not to have it call the button submit handler. Instead, it behaves just like the standard search button that views provides automatically.

How can I have my second button call a separate handler?

Below is what I've tried to do.

(FWIW, my specific goal is to let the user use the exposed view form to search for an existing node, then if he doesn't find it, to go ahead and post a new node. So, I want a button that will call an action to post a new node.)

function my_module_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'views_exposed_form':
      if ($form['#id'] = 'views-exposed-form-my-module-page-1') {
        // Add a button
        $form['my_button']['#type'] = 'button';
        $form['my_button']['#value'] = t('My Extra Button');
        $form['my_button']['#submit'] = array('my_module_button_handler');
      }
      break;
  }
}

function my_module_button_handler($form, &$form_state) {
  // do something here
}

The submit handler is not called by default on a form api element type "button". If you want to execute a submit handler on a button you will need to add

$form['my_button']['#executes_submit_callback'] = TRUE;

As a side note this will not be the case if the #type was 'submit' because the executes_submit_callback is by default equal to true on that element type.

Hope this helps.


Load form and use custom submit handler In my Controller I'm loading a form with the following code.

$form = \Drupal::formBuilder()->getForm('Drupal\custom_module\Form\CustomForm');

Depending on different cases I would like to use different processing of the form.

I see 3 possibilities to handle this:

Use different forms and load the correct depending on the case
Include some hidden fields and evaluate these fields in the submit handler of the form
Use different submit handlers

I think the third possibility is the best one. But when I try to use a custom submit hanlders.

$form['#submit'] = 'custom_module_form_submit';
// or
$form['actions']['submit']['#submit'][] = 'custom_module_form_submit';

They both don't work. How can this be achieved? Is there a better way of doing this?

@kiamlaluno is right, you have to use the form builder directly. But for this question in the comments there is a solution:

  ... its a custom class extending FormBase. But I still don't get how
  to change the submit handler. In my controller ...

you can put additional parameters in formBuilder()->getForm('Drupal\custom_module\Form\CustomForm', $param), which you then can use in the form class to build the form differently, for example add different submit handlers:

  public function buildForm(array $form, FormStateInterface $form_state, $param = NULL) {

    if ($param == 1) {
      $form['actions']['submit']['#submit'][] = 'custom_module_form_submit';
    }

  }


How do I get the public url of a file from the uri or filename I'm using php from with a view (Views PHP) I'm trying to extract the real url of a file from a file reference. I am able to get the the uri of the file and or the filename. What drupal function can I use to get thee actual public URL of the file?.

$videouri = db_query('SELECT filename FROM `file_managed` WHERE fid = ' . $nidvideo)->fetchColumn();
//drupal_set_message('<pre>'. print_r($videourl, TRUE) .'</pre>');
$realpath = drupal_realpath($videouri);
$videourl = file_create_url($realpath);
return($videourl);

What do you mean by "public URL" exactly ?
file_create_url() can give the absolute URL to the image out of the box.
$videouri = db_query('SELECT uri FROM {file_managed} WHERE fid = :nidvideo', array(':nidvideo' => $nidvideo))->fetchColumn();
//drupal_set_message('<pre>'. print_r($videourl, TRUE) .'</pre>');
$videourl = file_create_url($videouri);

file_create_url() expects a valid uri. drupal_realpath() gives the server path which does not work.
I also changed your database query to avoid any SQL injection vulnerable.


Drupal Adding Font Style to Date Fields Sorry i thought i should ask this here as apposed to your CSS site as ive a feeling its something that Drupal is doing and not just a general css question.

When viewing the last comment time on the right of the main table of this page (and taxonony table pages) you will see that something is adding an  tag to my date field.
My site with the em added

The norm12 span class is what i have added and you can see that even making the font-style: normal with important added its still showing it with  tags and style about it.

Its only a minor problem but its driving me mad.

Can anyone see where the problem may lie?

Thanks

Reg your trying override this on the span but the em tag has the style defined on it.

Should be...

.norm12 em {
//...
}


How do I include a React app? We are moving towards a hybrid-headless model with Drupal 7. All our data is exposed through RESTful and I have successfully built React app using the data.

How can pull that app in as a block? I put the code in a block and the app loses much of its styling and 1 third of the data is hidden. The basic functionality still works, but that's not enough.

Is there some trick to getting the a the full app to run correctly in a block?

Thank you

I solved this as follows:

install react-app-rewired:  npm i --D react-app-rewired --
this is important so you don't try to load react more than once
change package.json so build executes react-app-rewired build -- full instructions here: https://github.com/timarney/react-app-rewired
Pick a spot in your Drupal install for your react app  -- I chose sites/all/react, it seemed right to me
load react into your template using the CDN links https://reactjs.org/docs/cdn-links.html
update package.json with homepage for your app to reflect where you are saving it for example: "homepage": "/sites/all/libraries/myapp/",
build your react app and copy the contents of the build folder to the location you chose for storing your app
build a simple module to load your app as a block (code below)
add the block to your page however you see fit

/* Adds the block to the block menu */
function my_app_block_info() {
  $blocks['my_react_app'] = array( //a new array for each new app
    'info' => t('My React App'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

/* set the content for the block */

function my_app_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'my_react_app': //a new case for each new app
        $block['content'] = file_get_contents(libraries_get_path('appfolder').'/index.html');

        break;
     }
  return $block;
}

 /*
   file_get_contents loads the index.html page that loads
   the react app don't use libraries_get_path if you saved your app
   somewhere else
 */


PHP 5.2 or 5.3 for Drupal 6.22? I have noticed that PHP 5.2 is officially recommended for Drupal 5 and 6. But as the 'System Requirement' page needs update, I am wondering what would be the anticipated problems using Drupal 5.3.

I have been using PHP 5.3.2 + FPM on a Drupal 6.22 site, and have some JavaScript issues with the Voting UP/Down and Poll modules. Is it possible that I can resolve these by downgrading PHP to 5.2?

Drupal 6.22 is compatible with PHP 5.3, but some contributed modules may not support 5.3. That said, I have been developing D6 sites on 5.3 for more than a year without any problems.

Usually, the PHP version is not the cause of JS problems, so I would start to look for the solution elsewhere (Firebug?).


How to create a block that shows recently viewed products/nodes for users? I want to make a block that shows last viewed products for users (logged and anonymous), using Drupal 7 with Ubercart 3.

First, I tried to use the Recently read module. I don't why, but it's not working! Any changing in admin options (number of showing products and type of nodes) doesn't have any effect. And this block always shows ALL of my pages and products for all users.

Then I tried to do this using modules Flag + Rules + Session API. I found only a manual for Drupal 6.  But in section "Select the condition to add - Check a truth value" and Views configure it's not similar to Drupal 7.

Can anybody help me to implement this functionality? Maybe you know, why the Recently read module seems to not be working in my case, or maybe it causes some conflict? Or how to configure modules Flag + Rules in Drupal 7?

recently_read seems to have evolved
or do it with flag module (although not described in the linked tutorial, flag can also handle anonymous users)


Where does the drush installtation command set the PROMPT_COMMAND variable? I installed drush and as part of the installation it makes some changes to the command prompt.

...
# Optional. Enrich the bash startup file with completion and aliases.
drush init
...

Whenever I execute an command at the prompt I get the message:

bash: __drush_ps1: command not found

The env command displays PROMPT_COMMAND as

PROMPT_COMMAND=__git_ps1 "\u@\h \w" "$(__drush_ps1 "[%s]") \\\$ "

I think somewhere at the global level the PROMPT_COMMAND variable is set to that value but I can't locate it in any of the global environment variables and profile scripts.

Because drush was installed as root commands executed as root don't produce that error message. root has a .drush directory with some drush scripts.

The function that changes the .bash_profile or .bashrc file is drush_init_core_init(). The shell script that effectively sets the prompt is $home/.drush/drush.prompt.sh, where $home is the value returned from drush_server_home(). If the file doesn't exist, drush_init_core_init() creates it from the content of DRUSH_BASE_PATH . "/examples/example.prompt.sh", which contains the following line. (See example.prompt.sh.)

export PROMPT_COMMAND='__git_ps1 "\u@\h \w" "$(__drush_ps1 "[%s]") \\\$ "'

There is also the following line, which sets PS1 and that is is commented out by default. (See the comment before it.)

  # PROMPT_COMMAND is used in the example above rather than PS1 because neither
  # Git nor Drush color hints are compatible with PS1. If you don't want color
  # hints, however, and prefer to use PS1, you can still do so by commenting out
  # the PROMPT_COMMAND line above and uncommenting the PS1 line below:
  #
  # export PS1='\u@\h \w$(__git_ps1 " (%s)")$(__drush_ps1 "[%s]")\$ '

As for the error message you see, __drush_ps1() is a bash function used to change the prompt, defined in drush.complete.sh. bash completion/prompt broken explains exactly when and why you get that error. TLDR; in some circumstances, the shell script is not sourced, and the Bash function results not defined.
For what I understand it, the error has been has been fixed in recent versions, though, so you should just need to update Drush to fix the error.


Escape of Upscaling image in Scale and Crop option I am using Image Style with Scale and Crop option with the dimension 110 * 110. If the style applies on small image it upscales the size to 110 * 110. I don't want to upscale it. How to do that?

A separate scale image effect followed by a separate crop image effect won't give you what you want.
Imagecache Actions does not offer a single image effect that does what you want.

However, what you could do is use the aspect switcher image effect of imagecache_actions:

aspect switcher:

if portrait: scale to 110x(empty) (no upscaling)
if landscape: scale to (empty)x110 (no upscaling)

crop to 110x110


How to pre populate the commerce shopping cart with products Is there a way to pre populate the Shopping cart with all products similar to this example?
http://www.taytocrisps.ie/park/book_tickets

I only have 5 products on the site and I want to skip one step and add to all products to the cart. The user then selects the number of the products in the cart and goes straight to billing information and payment.

I implemented a hook_menu with callback that adds specific product variation from the arguments to the cart and then redirects the user to cart. With same logic you could toss in all the products you wish. Mayby just additionally check that that cart is initially empty.

function x_menu(){
    $items['tickets'] = array(
      'page callback' => 'x_tickets_callback',
      'access arguments' => array('access content'),
    );
    return $items;
}

function x_tickets_callback(){
    global $user;

    // mayby check that cart is empty here

    // you should get these really from some variable
    for($i = 1, $i<7,$i++){
      $commerce_product = commerce_product_load($i);
      // create line item from product
      $line_item = commerce_product_line_item_new($commerce_product);
      commerce_cart_product_add($user->uid, $line_item);
    }
    // prevent notification
    $messages = drupal_get_messages();
    drupal_goto('cart');
}


How to get a friend's education and work history information using FBoauth module Is there any way to get friend's education history and work history? I tried to send permission friend_education_histroy and friend_work-history on fboauth.fboauth.inc file. But I got an error.

How will I pass the permission to Facebook and get my friend's info?

You may want to check your permissions to make sure that FB hasn't changed anything as they are notorious for changing their code. Here are the Permissions Reference.


Where is the value in a form textfield stored? I have created a simple form that displays a textfield and a submit button. The text field is defined:

$form['upload_file'] = array(
    '#type' => 'textfield',
    '#title' => t('File to read')
  );

When I enter "test" in the textfield and select the submit button, the form moves on to the Validate function which has the following code:

$answer = $form_state['values']['upload_file'];
  if (!$answer) {
    form_set_error('upload_file', "Please enter a file name: ");
  }

And I get the error message indicting that $answer is empty. Do I have the wrong array location for the stored textfield text? Or is there something else I need to do to place the values in the form ito the values array?

The easiest way to debug form related issues I have found is with the devel module

drush dl devel && drush en devel -y

This module provides a whole host of helpful functions. E.g. in your case you could use this in your validation function:

dsm($form_state['values']);

This would print a lovely formatted array of every value in the form. From there you can drill down to the required value.

I believe you should be checking for:

if (empty(trim($form_state['values']['field_upload_file']))) {
  form_set_error('upload_file', "Please enter a file name: ");
}

Or alternatively, if you are just checking to see if the textfield simply has a value in it, then the better approach would be to use the FAPI and declare:

$form['upload_file'] = array(
  '#type' => 'textfield',
  '#title' => t('File to read'),
  '#required' => TRUE,
);


Permission Denied (403) using /batch I have run into a scenario where I am getting an 'Permission Denied' error when attempting to run anything that uses batch, with the sole exception being CRON.

First off, this error is NOT related to the max_allowed_packet issue referred two in every other thread regarding this scenario. First off, my max_allowed_packet is set to 16M, and second, my batch table shows valid requests waiting to be run:

my.cnf:

max_allowed_packet = 16M

drupal.batch table:

15456   ba_Tu-5BZEcFUq3RH37zvx6bvCWJGvlUUtYgADfOlPY 1406048062  ...

The requests being attempted are very small as well, I'm only trying to delete 1 user.

This happens with the primary admin account (UID 1) as well as all other administrators, so it does not appear to be account or access specific.

I am uncertain where to look next for more clues.

MySQL logs do not show any warnings or errors, and the only line in PHP is this:

php drupal: https://www.example.net|1406048063|access denied|X.X.X.X|https://www.example.net/en/batch?op=start&id=15456|https://www.example.net/en/admin/people|1||batch

IP and Domain censored from above log.

I have also confirmed that there is no '/batch/' folder in my Drupal route that could be messing with the url.

UPDATE

I have continued to investigate this as I do patching and upgrading to my network. As part of this overhaul, the backend DB was just switched from MySQL to PostgreSQL, and the issue persists on both databases. So database can been completely ruled out.

I have had success with disabling 'Clean URLs' in my config. If I disable them all batch operations work as expected, however I cannot leave them disabled for obvious reasons. Disabling them every time is not a great option either, as content admin do not have access to this setting and cannot delete spammers as a result.

I would look at your .htaccess rewrite rules. I've hit instances in the past where batch requests wouldn't fire during updates. Turns out I had custom .htaccess rewrite rules interfering with those requests.

Based on your example URL, it looks like you're running Drupal in a subdir on the domain. Have you set up the RewriteBase directive for that subdir? Do you have any other custom redirects in .htaccess?


How to reorder items of multi valued entity reference field alphabetically? I have a entity reference field, widget used is "Inline entity form - Multiple values". We can add multiple entries. When I have multiple values they are ordered by weights. How can I order them alphabetically ?

Try adding a customjs.js file to your Drupal site and reference it from basic.libraries.yml (in Drupal 7 its the theme.info file).

You could add there could acting upon your  items and sorts them alphabetically; There are many such JS codes (classic or Jquery).

See this JQ code pen for example.


How to enable the Webform module? The tick box is greyed out. What is the "Contribute" module and where can I find it?

You can found it at https://www.drupal.org/project/contribute

  The Contribute module adds a 'Community information' section to
  Drupal's status report (/admin/reports/status) which encourages
  individuals and organizations to join the Drupal community, become
  members of the Drupal Association, and contribute to Drupal projects,
  events, and more.

Maybe you should read this article: The Webform module now depends on the Contribute module


Facebook Autopost. Why I still receive download library message? I want to use Facebook Autopost. I have downloaded the facebok-php-sdk library and I have copied it to sites/all/libraries, but in status report I still receive this message. What should i do?

Please make sure that the facebook.php file is found at sites/all/libraries/facebook-php-sdk/src/facebook.php.


How to set default values for daterange widget in baseFieldDefinitions Everything is working in my code except the default values...

$rangedefaults['value'] = DrupalDateTime::createFromTimestamp(time());
$rangedefaults['end_value'] = DrupalDateTime::createFromTimestamp(time());

$fields['date'] = BaseFieldDefinition::create('daterange')
  ->setLabel(t('Date and time'))
  ->setDescription(t('When the activity takes place.'))
  ->setRequired(false)
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'daterange_default',
    'weight' => -4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)
  ->setDefaultValue($rangedefaults);

What is the proper way to set default values for this widget?

I think the problem is just the date format. If you look at the DateRangeItem class's generateSample method, it uses the DateTimeItemInterface::DATETIME_STORAGE_FORMAT format to prepare both value and end_value. You probably just need to do the same:

$rangedefaults['value'] = $rangedefaults['end_value'] = (new DrupalDateTime())->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);

As an aside, since you're using the current time it feels like you might want the default value to be the time at which the entity is created. By setting it in the field definition, the default will always be the time you installed the field.

That might be what you want, but in case not, use setDefaultValueCallback instead, and add a method to the entity class which returns the default value.


How do I fix this error? I am getting an error right after creating the tweet.libraries.yml file as per istructions given from a book about Drupal 8 theming. Can anyone help me fix this error?

  The website encountered an unexpected error. Please try again later.
  Error: Cannot use assign-op operators with overloaded objects nor string offsets in Drupal\Core\Asset\LibraryDiscoveryParser->buildByExtension() (line 138 of core/lib/Drupal/Core/Asset/LibraryDiscoveryParser.php).
  Drupal\Core\Asset\LibraryDiscoveryParser->buildByExtension('tweet') (Line: 87)
  Drupal\Core\Asset\LibraryDiscoveryCollector->getLibraryDefinitions('tweet') (Line: 66)
  Drupal\Core\Asset\LibraryDiscoveryCollector->resolveCacheMiss('tweet') (Line: 148)
  Drupal\Core\Cache\CacheCollector->get('tweet') (Line: 44)
  Drupal\Core\Asset\LibraryDiscovery->getLibrariesByExtension('tweet') (Line: 58)
  Drupal\Core\Asset\LibraryDiscovery->getLibraryByName('tweet', 'bootstrap') (Line: 54)
  Drupal\Core\Asset\LibraryDependencyResolver->doGetDependencies(Array) (Line: 31)
  Drupal\Core\Asset\LibraryDependencyResolver->getLibrariesWithDependencies(Array) (Line: 104)
  Drupal\Core\Asset\AssetResolver->getLibrariesToLoad(Object) (Line: 116)
  Drupal\Core\Asset\AssetResolver->getCssAssets(Object, ) (Line: 291)
  Drupal\Core\Render\HtmlResponseAttachmentsProcessor->processAssetLibraries(Object, Array) (Line: 161)
  Drupal\Core\Render\HtmlResponseAttachmentsProcessor->processAttachments(Object) (Line: 45)
  Drupal\Core\EventSubscriber\HtmlResponseSubscriber->onRespond(Object, 'kernel.response', Object) (Line: 111)
  Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.response', Object) (Line: 179)
  Symfony\Component\HttpKernel\HttpKernel->filterResponse(Object, Object, 1) (Line: 161)
  Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 62)
  Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
  Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 48)
  Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 98)
  Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 77)
  Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
  Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
  Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
  Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 628)
  Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

This is the content of the tweet.info.yml file.

    name: tweet
    type: theme
    description: 'A twitter Bootstrap starter theme'
    core: 8.x
    base theme: false

    libraries:
      - tweet/bootstrap

This is the content of the tweet.libraries.yml file.

    bootstrap:
      version: 3.3.6
      css:
        theme:
          css/bootstrap.min.css: {}
          css/bootstrap-theme.min.css: {}
      js:
        js/bootstrap.min.js
      dependencies:
        - core/jquery

Change the tweet.info.yml file as follows.

name: 'tweet'
description: 'A twitter Bootstrap starter theme'
core: 8.x
type: theme
base theme: false

libraries:
  - 'tweet/bootstrap'

Put the following in the tweet.libraries.yml file.

bootstrap:
  version: 3.3.6
  css:
    theme:
      css/bootstrap.min.css: {}
      css/bootstrap-theme.min.css: {}
  js:
    js/bootstrap.min.js: {}
  dependencies:
    - core/jquery

Also, be sure you have a tweet.theme file in the same directory. This file is necessary for Drupal to recognize the directory contains a theme.


Use hook_hook_info() to implement hook_form_FORM_ID_alter()s in a separate file I have a lot of mymodule_form_FORM_ID_alter()s in my module and I want to move them to a separate file (mymodule.form.inc), I found hook_hook_info() but I couldn't figure out how to use it for that specific case.

I tried adding:

$hooks['form_alter'] = array(
  'group' => 'form'
);

to mymodule_hook_info() but it didn't run the form alterers that I moved to the separate file. Any ideas how to get it to work?

It works pretty well, the only thing is that if you want to implement hook_form_FORM_ID_alter(), you need to add:

  $hooks['form_FORM_ID_alter'] = array(
    'group' => 'form'
  );
  return $hooks;


Ubercart shipping API, get the package object with php to send the tracking number to the client as email I have an online shop implemented in Ubercart 6.x-2.4 and Drupal 6.19

All cool everything works but I'm struggling to do custom things

What I want to do is after saving the shipment data (i'm insterested in sending the Client that the package has been sent and he has to receive by email the tracking number)

So I added a predicate that does just that, but I don't know how to get the shipment object associated with the order and get that tracking number. I just know that there is an API somewhere...

Are you managing to save the tracking number to the order? With a bit of preprocess magic you could probably get the number as a variable to the invoice template that already gets sent out.

EDIT:

Something like the below would work, that I did to get extra data displayed in an invoice. I did this in my theme, so replace that with your own theme name (and the other capitalised bits).

    function [THEMENAME]_preprocess_uc_order(&$variables) {
        $variables['tracking_number'] =
           db_fetch_object(db_query("QUERY TO GET TRACKING NUMBER"))->COLUMNNAME;
    }

Then if you put uc_order.tpl.php (needed as a dummy file so your theme can override other templates) and your own custom template into your theme directory then you are able to reference it in the template with a simple call like print $tracking_number;


How to disable views pager programatically in certain cases I have a paragraph which shows a view. The editor may set some options as argument filters, sort and show/hide pager. "Normal" fields are used to collect these options and template_preprocess_paragraph__PARAGRAPH_TYPE actually builds the view. The filtering works well, but I am not able to get rid of the pager if the editor desires to disable it while limiting the amount of items shown at the same time ($view->setItemsPerPage(0); is not an option here). Here is some simplified code from mytheme.theme:

function mytheme_preprocess_paragraph__content_list(&$variables) {
  $view = Views::getView('content_list');
  if (!$view) {
    return;
  }

  // Simulate user input:
  $order = 'DESC';
  $disable_pager = TRUE;
  $items_per_page = 12;
  $filter_args = [1,2,3,4];

  $display_id = 'embed_content_list_title';
  $view->setDisplay($display_id);
  $view->setHandlerOption($display_id, 'sort', 'title', 'order', $order);

  if ($disable_pager) {
    $display = $view->getDisplay();
    $pager = [
      'type' => 'none',
      'options' => [
        'offset' => 0,
        'items_per_page' => 50,
      ],
    ];
    // This doesn't work:
    $display->setOption('pager', $pager);
    $display->setOverride('pager', $pager);
    // This neither works:
    $view->display_handler->setOption('pager', $pager);
    $view->display_handler->setOverride('pager', $pager);
    // I also had no luck with:
    $view->pager = NULL;

    $view->setItemsPerPage($items_per_page);
  }

  $view->execute();
  $variables['content']['content_list'] = $view->buildRenderable($display_id, [$filter_args]);
}

How can the pager be disabled in above code? A workaround might be using different displays, one with pager enabled and another with pager disabled. But I would prefer to solve it with just one display (as I already have multiple displays and would have to build both versions for each display).

Piggybacking off How to set views pager item size programmatically? and looking at PagerPluginBase.

To change values

if ($disable_pager == FALSE) {
  $view->setOffset(0);
  $view->setItemsPerPage($items_per_page);
}

Now to answer your question

  How can the pager be disabled in above code?

You can disable it by setting items per page to zero.

$view->setItemsPerPage(0);

If you want to limit the amount of items without pager, all you have to do is unset it.

   $view = Views::getView('content_list');
   $display_id = 'embed_content_list';
   $view->setDisplay($display_id);
   $view->setItemsPerPage(12);
   $view->execute();
   unset($view->pager); // must put this unset after the $view->execute();
   $variables['content']['content_list'] = $view->buildRenderable($display_id, [$filter_args]);


How to grant only certain roles permissons over certain field? I have a content type with a number of fields. But one of the fields in the edit form must be seen by administer and people with "Reviewer" role. How can i do it?

Field permissions module now has a release candidate version for D8, this is the way to implement Role-based fine-grained control over fields.

When you enable that module edit the Content type fields you want custom permissions on, you will see a new option Field visibility and permissions where you can choose Custom permissions.

When you tick that option a table will appear listing Create, Edit and View permissions and all the Roles you have defined on the system. Add the Reviewer role to the ones who can Edit the field (Administrator is granted all by default), and adjust the other permissions as needed.

A new menu item will appear under Reports > Fields > Report all field permissions /admin/reports/fields/permissions where you can see all the Fields custom configuration in one place.


Drupal for Firebug does not work in FF> Works fine in Chrome I have downloaded and installed Drupal for firebug Module and FF and Chrome extensions.

I log in as admin (uid 1) and do a simple output call:

firep("this is some message", "Message Title");

On chrome I can see the output fine, but in firefox I get the following message:

  No Drupal for Firebug data was found.

Either this site is not running Drupal or the Drupal for Firebug module has not been installed/enabled.

There are some issues with the Drupal for Firebug plugin depending on which version of Firefox/Firebug/DrupalForFirebug you are running.  See the following issue on DO Extension breaks with version 14 of Firefox

It works for me on:

Firefox - 18.0.2
Firebug - 1.11.2
Drupal for Firebug Module - 7.x-1.4
Drupal for Firebug Firefox Plugin - 2.2


Conditional fields in views drupal 6 I am using conditional field in content type.

Is it possible to do the same in views
i want to show one field dependent on value of first.

Thanks

Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy)
with fields in views.

  Conditions include:

  Equal To
  Not Equal To
  Greater Than
  Less Than
  Empty
  Not Empty

For D6

Views - Control field display

  It provides a views filter that allows users to control which fields
  are displayed.

  To use, install the module, then add the Global: Control field
  visibility filter to your view. Select which fields are controllable
  (either defaulting to visible or invisible). This will add an exposed
  element that allows users to toggle the fields you specify on or off.


Manually post to search results page I have a section in my theme where I'd like to manually include a search input.  I do not want to use the search block as I have some additional customizations I'm integrating outside of the scope of this question.

It looks like the default search form posts to the existing page and redirects to the results page (/search/node/query).  How can I manually trigger this to happen?

I've tried to mimic the form_id but it doesn't seem to pick it up:

<form method="post" action="">
    Search:
    <input type="text" name="search_block_form" ng-model="query" />
    <input type="submit" value="Search" />

    <input type="hidden" name="form_token" value="">
    <input type="hidden" name="form_id" value="search_block_form">
</form>

There is an additional field in the default block called form_build_id but it
changes each time the form is rendered.

How can I accomplish manually creating a POST to go to search results?

Drupal core search result pages do not listen to URL Parameters or HTTP POST content.
Instead, it takes the third part from the search/node/QUERY URL format, and shows results for QUERY.

This unfortunately makes it not possible to use a standard HTML form created without Drupal's form API. There are of course workarounds.

Basically what we try to do is route the user's search query to the search/node path. I can see you are using Angular. You might be able to make it send the user to the proper path.

Alternately, you can make Drupal listen to URL parameters or the HTTP post request content.

https://www.drupal.org/project/query_parameters_to_url - this module I just found (and did not try personally) appears to rewrite URL parameters to a path query. I'm not sure this will work for search forms though.

If not, you will have to create a custom module, and take over the search result page callback. Then, it can show appropriate results or call the old page callback function with the search query taken from alternative sources.


How to add custom css classes to views exposed filters? I would like to add custom css classes to specific views exposed filters. Is this possible either by default or with some Drupal module?

UPDATE: Please, note that I am not referring to the views exposed filters form in general, but individual filters, eg. a class to a date filter, another class to an entity reference filter, etc.

Have you considered something like this?

`.view-[viewname] .views-exposed-widgets`

You could use:

theme_form_alter(&$form, &$form_state, $form_id)

Check for the view/form id,  and then add classes:

$form['#attributes']['class'][] = 'test';


8.3: How to create a node via REST with html? I have a Drupal 8.3 setup and working and want to add content via REST. I can create nodes fine, but only in plain text. I can't figure out and can't find any documentation for how to submit content as html so it could have formatting.

I found a comment that had examples for submitting comments with basic html with the body specified like:

{"content_body": {"format": "basic_html", "value": "Hi"}

But when I tried to do something similar with the 'body' tag for posting to /entity/node, it returns a 422 response with this message:

Unprocessable Entity: validation failed.\nbody: Body: this field cannot hold more than 1 values

For reference, this is basically the hal+json body of the post (minus the taxonomy stuff not relevant to this question):

{
  "body": {
    "format": "basic_html",
    "value": "This is the body of the test"
  },
  "title": {"value": "Test One"},
  "type": {"target_id": "Article"}
}

If I drop the 'format' tag from the body dictionary, everything works fine... except the tags are displayed and not interpreted as html.

Thanks in advance.

Drupal is probably expecting an array of field data, even if the field itself only accepts a single value.

When the JSON is decoded, this is still an array:

{
  "format": "basic_html",
  "value": "This is the body of the test"
},

But with 2 items, when only one is expected.

You should be able to fix by providing an array with just the one item:

"body": [{
  "format": "basic_html",
  "value": "This is the body of the test"
}],


REST API OAuth Authorization and Authentication I am very much confused about the way OAuth authorization and authentication works in Drupal 8/9.
Let me put my points first, please correct me if I am wrong.

Authorization is when an entity proves a right to access.
Authentication is when an entity proves an identity.

I have done the following to implement a REST API which is intended to be consumed by mobile applications (Android and iOS).

Installed and/or enabled modules: Simple OAuth, REST UI, RESTful Web Services, Serialization.
Created a new role for specifying the scope of simple OAuth consumer, and set required permissions.
Created a consumer by adding RSA key pair, password and scope.
Succeeded in getting the response from /oauth/token by submitting a request body containing grant_type, client_id, client_secret, username and password.

The question is, why we need to send the username and password, for getting the access_token, since we are only trying to Authorize the API Request and NOT Authenticate the User?
Also, what should I do to Authorize the API request with OAuth but need to access contents without authentication? Should I create a dummy user and always send this user credentials to get access_token?
It would be very helpful if someone can explain the concept and how should one proceed.
Reference I followed: https://dev.acquia.com/blog/decoupled-drupal-authentication-oauth-20

Actually, I got the solution. It was my mistake, that I was trying to use OAuth2 3-legged authorization, but I am actually need OAuth 2-legged authorization.
More Details on oAuth Flow and Grant Types: oAuth Grant Types


What happened to array-shift.com (Drupal Stackoverflow Clone) It's interesting that there is no (recent) Drupal implementation of SO-like features.  I (and others) have a need to have an SO clone that has areas for private data (corporate owned), so we cannot use SO or the StackExchange engine.  I had high hopes for http://drupal.org/project/arrayshift, but it's fallen into disuse (and the demo site has been down for months).

Any suggested alternatives?  We've looked at OSQA and Question2Answer, and both seem like an annoying integration mess for user profile information.

What "happened" is what commonly happens to an idea that is generally solid but not (yet) popular: it's not being used and therefore not being actively maintained.

The best way to combat "disuse" is to use it. Create your own sandbox copy and start improving it. Ask Eaton for permission to take over the module and he'll give it to you.