Can users be forced to insert only plain text by default in CKEditor?

You want to change the ckeditor configuration to always paste as plain text.
This defined in https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-forcePasteAsPlainText
It comes down to the following JavaScript configuration:
// All content will be pasted as plain text.
config.forcePasteAsPlainText = true;

Have a look here for where to set it
Is there advanced configuration for CKEditor in Drupal 8?
Or just use module CKEditor custom config and set in custom configuration: forcePasteAsPlainText = true


Just remove access arguments, when the callback is set to TRUE you dont need any parameters:

$items['browse/restaurants'] = array(
  'title' => t('Browse Restaurants'),
  'page callback' => 'list_restaurants',
  'access callback' => TRUE,
);


If that's the exact code, then

var regex = /Keywords(.*)Description/;

should be

var regex = '/Keywords(.*)Description/';


$view->args[0] returns the first argument.


Change product price before putting it on a cart

You want to alter the cart item, not the product node. hook_uc_cart_alter is what you're looking for.

function MYMODULE_uc_cart_alter(&$items) {
  foreach($items as $key => $item) { //Set all items to $3.50
    $item->price = 3.50;
  }
}


OK! After going back and forth between var_dump's, installed modules list and hooks, I discovered that the ONLY hook that will update the page's tags is hook_metatag_metatags_view_alter(&$output), in which something like this needs to be done:

$output['title']['#attached']['metatag_set_preprocess_variable'][0][2] = "Custom title";

My n00b diagnosis is that this hook is called right after the last Metatag module's function that rebuilds the metatags from scratch, and therefore it's the only one that matters.

Hope this will help others! :)

~Steph


you Could create your own display mode using see this Then you create a menu route using hook_menu, similar to this:

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

$items['node/%node/viewmode2'] = array(
'title' => 'Test',
'page callback' => 'yourModule_page_callback',
'page arguments' => array('node', 1),
'access arguments' => array(1),
'type' => MENU_CALLBACK,
);

return $items;
}

function yourModule_page_callback($node) {
 // here you render the node with the view mode 2
 $node_view = node_view($node, 'view_mode2_key');
 $rendered_node = drupal_render($node_view);
 return $rendered_node;
}

for the other view mode you could use the default display mode on  node/node_id or you could create extra one with same approach


How to override node comment form template?

In Drupal 7, and in the case of the user login form, your trick works because the form doesn't set the #theme property; in that case, Drupal will use the theme function whose machine name is equal to the form ID. (For the login for, that is user_login.)
That is not true for the comment form, for which its form build (comment_form()) sets the #theme property.

$form['#theme'] = array('comment_form__node_' . $node->type, 'comment_form');

There isn't a match between the machine name of the theme the form builder wants to use, and the comment-edit form ID; the latter is comment_node_CONTENT_TYPE_form, not comment_form__node_CONTENT_TYPE. If you were defining a comment_form theme function, that should work.

In Drupal 6, there is no #theme property for comment_form, which is the form ID of the comment edit form.


How to access the user's email field with Field Permissions?

I think your issue here is a duplicate of this one:
https://stackoverflow.com/questions/2727513/drupal-show-hide-fields-in-view

The two solutions are:

in the field template, display the content depending on the user role
or
create two views displays, one for each of your user role


How to add default text that clears on focus to a form in Drupal?

What you want here is:-

a) hook_form_alter to change the form

b) #attached to add JS to the form

c) add clear-text to ['#attributes']['classes'] where necessary.

Then you can use this little JS.

 Drupal.behaviors.clearText = function(context) {
    var inputs = $('input.clear-text:not(.processed)');

    // Store the original values
    inputs.each(function() {
      $this = $(this);
      $this.data('default', $this.val());
    }).addClass('processed');

    // Set up inputs to clear on focus & reload default (if blank) on blur
    inputs
      .focus(function() {
        $this = $(this);
        if ( $this.val() == $this.data('default') ) {
          $this.val('');
        }
      })
      .blur(function() {
        $this = $(this);
        if ( $this.val() == '' ) {
          $this.val( $this.data('default') );
        }
      });
  }


The module does not dissapear after disable, uninstall, clear cache and cron job

This module might live in a profile or in a directory that is not sites/all/modules. It is possible to have the same module in multiple places in Drupal at the same time.

You should open up the database, go to the system table and look for the entry for file_entity and see what the path is. That will tell you. You could also grep your codebase for "File entity" or "file_entity" which should also produce results.

If not, perhaps you are on a dev/stage environment? Did your FTP program actually delete the files? Check that there wasn't a permission issue regarding deleting that.

edit: if this is an older release of the media module, it used to ship with file_entity under media/modules/file_entity if I recall. Also check there. If that is the case, what you should do is completely upgrade the media module to the latest version, which looks like rc2 right now.


Search option just as that provided in drupal.org

Facetapi module will help you. From facetapi module page:

  The Facet API module allows site builders to easily create and manage
  faceted search interfaces.

You may also look into search_api module. From module page:

  This module provides a framework for easily creating searches on any
  entity known to Drupal, using any kind of search engine. For site
  administrators, it is a great alternative to other search solutions,
  since it already incorporates facetting support and the ability to use
  the Views module for displaying search results, filters, etc.

If you do not want to use the default Drupal search you can use apachesolr search module. This module can also be integrated with facetapi module.


How do I insert multi image with restFul service?

I think what you really want is to end up with something more like:

'field_gallery[und][0]' => 2381,
'field_gallery[und][1]' => 2375,

The second level of array indexing is the field position. So the first file id goes into [0] and the second into [1].


Solved thanks to https://stackoverflow.com/questions/27907044/htaccess-rule-to-remove-index-php-from-the-end-of-my-urls

Modified part of Drupal's .htaccess. Important to add new rule before standard index rewrite:

# Remove trailing /index.php that comes from external links.
RewriteCond %{THE_REQUEST} /index\.php [NC]
RewriteRule ^(.*?)index\.php$ /$1 [L,R=302,NC,NE]

# Pass all requests not referring directly to files in the filesystem to
# index.php.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]


Views: filter content by two taxonomy terms

Create three contextual filters: 1) global null (it's at the bottom), this will ignore the first argument 2) normal contextual filter for the first vocabulary, 3) normal contextual filter for the second vocabulary.

By normal I mean that you first select Term ID then Specify validation criteria, Taxonomy term, pick your vocab, Term name converted to term ID. It's a good idea to give these filters an Administrative title found under the More section, so that you can keep track which is which, as they need to be in the right order.

To reduce duplicates, in the view details "Advanced" > "OTHER" > "Query settings", check the box "Distinct" (thanks user2171413).


This depends ... D6 or D7 ... is the field a reference to something else (term, node, entity)?

Generally you have to write something that looks up the value of the item in the list, for example for a node reference:

  $modelcode='Toyota';

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
        ->fieldCondition('field_models_code', 'value', $modelcode, '=');
  $result = $query->execute();
  $model_nid=array_shift(array_keys($result['node']));

  unset($result);
  unset($query);

Then you would take the $model_nid and update your field in the form state:

$form_state['values']['field_model'][LANGUAGE_NONE][0]['value'] = $model_nid;

This example assumes D7 and a field set to node reference.


How to switch OG group members in bulk to another group

OK. Finally got it right. The easiest way to do this is to do a dump of the og_membership table into a text file.

Then run a "search and replace" for the gid, replacing the old gid with the new one. A simple word processor is ideal for this. Any string replacement can be handled this way.

Then importing that text file into the og_membership table.

Voila! All members have switched to the new group and they don't even know it! :)


How much server-side resources does the Omega theme use? Is the Omega theme scalable?

Yes there is some extra overhead involved (especially at the templating level); how much this will effect your response times will completely depend on the setup of your server. An easy test would be to enable the basic Garland theme, profile the site, then enable the Omega based theme and do the same. You should get a pretty good idea of how much extra overhead you're likely to get for a single page load.

If you're able to, go further. Stress test your server (using something like ab) with both themes enabled. That'll give you an even better idea.

If you've got a site with 100,000+ visitors per day though, your efforts might be better spent setting up a decent caching strategy, both in Drupal and on the web server. That will help to offset a lot of the overhead that Omega/Alpha can add.


Function to get all the user permissions

There is a Drupal function for that, user_permission_get_modules(), which returns an associative array, whose keys are the permissions and values are the modules that define those permissions.

If you only need the permissions without the module names, you can use array_keys:

$permissions = user_permission_get_modules();
$permissions = array_keys($permissions);


Programmatically set the value of a multi-value field from multiple arrays

Educated guess: (The key was to merge the arrays by using array_merge())

// Put all values in an array().
$AllItems = array_merge($FruitsCategory, $DrinksCategory, $DrinksCategory); // use array_merge

foreach ($AllItems as $Item) {
  $article->field_article_all_items[] = ['target_id' => $Item];
}

$article->save();

Also it can be used within the node creation:

// Put all values in an array().
    $AllItems = array_merge($FruitsCategory,$VegetablesCategory,$DrinksCategory);

// Create a new "Article" node.
    $article = \Drupal\node\Entity\Node::create([
        'type' => 'article',
        'title' => Test,
        'langcode' => 'en',
        'uid' => '1',
        'status' => '1',
        'created' => $current_time,
        'field_article_all_items' => $AllItems,  // use array_merge
        ]);
// Save the created node.
    $article->save();


Change Login Form:Username to Select Text

Yes we can do it using function hook_form_alter(&$form, &$form_state, $form_id) {}

Just include this function in template.php of your theme or in you module.

If you theme name is "testtheme" then replace hook with you theme name(testtheme).

OR
you can include it in your custom module. If you have custom module with name "testmod"  then just add this code in your module and replace the hook with your module name (testmod)

function **hook**_custom_form_alter(&$form, $form_state, $form_id){

    //Get the users  from database or keep it static according to requirement
    $users  =   array("user1"=>"User 1","user2"=>"User 2","user3"=>"User 3");
    if($form_id=="user_login"){
    $form['name']['#type'] = "select";
    $form['name']['#options'] = $users;
    $form['name']['#required'] = true;
   $form['name']['#size']='auto';

    }

    }

Don't forget to clear drupal cache.
Hope it will help!


If Drupal Commerce Cart is not Empty, add a class to body

Using this resource and thanks to @rémy I come up with this solution:

function THEME_preprocess_html(&$vars) {
    global $user;
    $cart = commerce_cart_order_load($user->uid);
    foreach (entity_metadata_wrapper('commerce_order', $cart)->commerce_line_items as $delta => $line_item_wrapper) {
      if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
        $vars['classes_array'][] = 'cart-loaded';
      }
    }
}

  So after a while of testing I ended up with an error with anonymous
  users, so I digged a little bit deeper and come up with something new
  and no errors this time:

function THEMENAME_preprocess_html(&$vars) {
    global $user;
    $quantity = 0;
    $order = commerce_cart_order_load($user->uid);
    if ($order) {
        $wrapper = entity_metadata_wrapper('commerce_order', $order);
        $line_items = $wrapper->commerce_line_items;
        $quantity = commerce_line_items_quantity($line_items, commerce_product_line_item_types());
        if ($quantity) {
            $vars['classes_array'][] = 'cart-loaded';
        }
    }
}


Does cron queue manage max_execution time?

To answer the question in the title, Drupal cron does check the time used to process the items in a queue, and by default it gives 15 seconds to each queue. This still doesn't avoid the total time given to all the queues doesn't exceed the limit, especially if the call to drupal_set_time_limit(240) (which would set the time limit to 240 seconds) doesn't have success.

Also, since the code used by Drupal is the following one (see drupal_cron_run()), if processing a single item in a queue requires more than the time assigned to processing a queue (for example 30 seconds instead of 15), Drupal cannot block processing a queue when the time assigned to a queue is passed.

  foreach ($queues as $queue_name => $info) {
    if (!empty($info['skip on cron'])) {
      // Do not run if queue wants to skip.
      continue;
    }
    $callback = $info['worker callback'];
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
    $queue = DrupalQueue::get($queue_name);
    while (time() < $end && ($item = $queue->claimItem())) {
      try {
        call_user_func($callback, $item->data);
        $queue->deleteItem($item);
      }
      catch (Exception $e) {
        // In case of exception log it and leave the item in the queue
        // to be processed again later.
        watchdog_exception('cron', $e);
      }
    }
  }

If you get a maximum time execution error, you can just limit the number of processed items, or assign less time for your queue.

function my_module_cron_queue_info() {
  $queues['my_module_batch'] = array(
    'worker callback' => '_my_module_process_queue',
    'time' => 3,
  );
  return $queues;
}

As side note, setting 'skip on cron' to FALSE is useless, as Drupal assumes it is FALSE by default. In fact, it uses if (!empty($info['skip on cron'])) {} to decide if skipping a queue; !empty($info['skip on cron']) is FALSE when $info['skip on cron'] is not set, or when it is set to FALSE.


Tag & vocabulary module or technique that mimics stack exchange tag behavior?

The Autocomplete Deluxe module is perfect for this. It adds an enhanced autocomplete element, that uses the JQuery UI autocomplete. Although it will not provide the term count, the behaviour is similar to stack exchange in every other way.


Displaying Empty Option in Multiselect box

That behaviour is by design; from the docs for form_process_select():

  // A non-#multiple select needs special handling to prevent user agents from// preselecting the first option without intention. #multiple select lists do// not get an empty option, as it would not make sense, user interface-wise.

(emphasis mine).

If you want to override that behaviour you can probably implement hook_element_info_alter() and provide your own process function which does things differently to the core one. e.g.

function MYMODULE_element_info_alter(&$type) {
  $type['select']['#process'] = array('MYMODULE_form_process_select', 'ajax_process_form'),
}

function MYMODULE_form_process_select($element) {
  // Duplicate code from form_process_sleect() and change what you need.
}


How to add a table to a Webform or EntityForm

A combination of EntityForms and TableField should get you going.

  This module allows you to attach tabular data to a node in Drupal 6 or
  any entity in Drupal 7.


Possible with

ThemeKey
ThemeKey Properties


How to collect a list of file URLs using Rules and send a single email containing that list?

Concatenating text in Rules was difficult when I did it. What I did was to keep two variables: a text array with a starting element value (such as "This is a digest:...") and a text value.

For each iteration of a loop over items to concatenate into a digest, etc. I set the text value to be the first item in the array ([array:0]) and then set the [array:0] value to be a concatenation of the text value and the new value from the loop. When the loop finishes, you know the [array:0] has the digest content.

I do not know why this couldn't work in a simpler way by concatenating the text value each loop directly or using two text values instead of an array. When I tried either of the other ways it only kept the last item or first item of what was being concatenated.


Optionally redirect a content to another url?

I think you could handle this in a views row level template file.

First set up a field for the redirect which is optional. Then add it to your view. Create the appropriate views row template file. In your template file print out the fields individually adding a bit of logic around the read more link:

<?php if ($fields['news_url']): ?>
  <?php print $fields['news_url']; ?>
<?php else: ?>
  <?php print $fields['readmore']; ?>
<?php endif; ?>

Obviously the field names are wrong but hopefully this gives you the idea.


Commerce Rule For Sales Tax On Shipping To One State

No idea why your rule isn't triggering based on the state. From the label, it looks like you're trying to apply taxes to the order total including shipping. So you need two things here you need to configure a state specific tax rule and then you need a shipping rule, and a second shipping rate calculation which applies your tax to your shipping rate. Hope that helps.


Filter Taxonomy Widget Options by Entity Reference

It is possible and can be implemented using Simple Hierarchical Select. From the modules page-

  Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.

Expose the view filters (course and course goals) in your case after you set the field type to simple hierarchical select. This guide might be helpful.


How to access and edit files from admin panel?

Try elfinder File Manager module, which also allows inline text file editing, besides other file managing operations.


Brightcove Connects breaks site after core upgrade to 8.5.x in Acquia Cloud

I discovered the issue. Case-sensitivity of the class names. Class "brightcove/src/Entity/BrightcovePlayer.php" extends "BrightcoveCmsEntity", while class "brightcove/src/Entity/BrightcoveCMSEntity.php" is named as "BrightcoveCMSEntity".

I replaced all instances of "BrightcoveCmsEntity" with "BrightcoveCMSEntity", and the issue was resolved, it exposed the same issue with "BrightcoveVideoPlaylistCmsEntity".

Fatal error: Class 'Drupal\brightcove\Entity\BrightcoveVideoPlaylistCmsEntity' not found in /mnt/www/html/nhradev/docroot/modules/contrib/brightcove/src/Entity/BrightcoveVideo.php on line 75

Replacing all instances of "BrightcoveVideoPlaylistCmsEntity" with "BrightcoveVideoPlaylistCMSEntity" resolved all issues.

The plugin now works as expected in Acquia Cloud.

NOTE, the code worked locally because I am developing on Windows.

Files touched:
brightcove/src/Entity/BrightcoveCMSEntity.php
brightcove/src/Entity/BrightcoveCustomField.php
brightcove/src/Entity/BrightcovePlayer.php
brightcove/src/Entity/BrightcoveVideoPlaylistCMSEntity.php

brightcove/src/Entity/BrightcovePlaylist.php
brightcove/src/Entity/BrightcoveVideo.php
brightcove/src/Entity/BrightcoveVideoPlaylistCMSEntity.php
brightcove/src/Form/BrightcoveVideoPlaylistForm.php

Reference: https://www.drupal.org/project/brightcove/issues/2969674


How to use Views/Contextual Filters with a referenced entity

Did you try to use module EVA: Entity Views Attachment it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

There is a screencast on how to use that module

hope that helps for you...


Your code looks fine to me. I think you might be on to something with your last comment, there might be something interfering with the hook.

One thing you might wanna do is run module_implements and look for the submit hook. That should give you a list of modules that implement that hook. At the very least you can check to see if there is anything strange going on with those modules.


Calendar View of a Field Collections and Contextual Filters

Got it. I started out creating a View from a Template.

Then, I decided to use a module called FullCalendar which is super easy to configure.

And here we go!

There is still some configurations to set in place but for the most part, this issue has been solved.


Go to Config > People > Account Settings > Manage Fields

Then, you can add fields to user profiles just as you would add fields to any content type. When you add fields here, there is a checkbox to "Display on user registration form" if you want the field to be part of the user's registration process.

Hope this helps someone.


There is something else you should check. If this is a new site, and you have newly named regions, make sure that the regions have underscores (instead of dashes.) If you need to convert any dashes to underscores, you'll have to reassign and re-enable the blocks on the Structure > Block Layout page.


Is there a token I can use to display a node's view mode?

Look at the Advanced Entity Tokens module.

  Advanced Entity Tokens (AET) Creates a Token for each of your entity
  items.

  Through AET you can query the DB for entities using Tokens.

  Examples

  [aet:node:1] will return the 1st node with the token view mode (or
  full if token is not available).
  [aet:file:1:view-original] will
  return the 1st file entity with the original view mode.
  [aet:taxonomy_term:1:name] will return the 1st node title field (note
  that this level of chaining is done by the formal token implementation
  of the node entity in token/token.tokens.inc -> token_token_info()).

  Real World Examples

  Displaying a node inside a block: This could be done using Node Block
  OR you could insert a token inside a block you create through the
  Blocks interface that retrieves a certain node (or a property inside a
  node, [aet:node:] or [aet:node::body]) with no extra code.
  Displaying a File Entity (image) inside a title field: I'm not sure
  how this could have been done without custom code, BUT with AET you
  could easily insert the Token for a specific File Entity
  ([aet:file:]) and your entity will be displayed. AET defaults to
  the Token view mode if available (full otherwise), but you could just
  as easily specify a view mode of your own
  ([aet:file::view-teaser]).
  I'm saving this spot for real life
  examples other Drupal users had (or thought of having) for this
  module.


RedirectResponse not able to redirect in hook_entity_view drupal 8

Thank you, I got it working.
Don't need to return the object of RedirectResponse. It works like this.

$response = new RedirectResponse($redirect_url);

$response->send();

It works this way.


Change error message generated by webform for duplicate email submission

There's other way if you don't want to code anything.

You can use String Overrides  Module

  This module allow override any translatable string on the site.


How to get vote results from node reference through views?

Can you add a relationship of referenced node? or referenced write a review?

If not use the entity reference module instead. Add an entity reference field, with auto complete widget. Bundle type: Node.

Then in view add a relationship of referenced write a review.


When directly loading a Commerce 2 Order Item, why is the entity cached for anonymous users?

The issue was due to the fact that the entity logic was running in a custom form and the form was caching the entity.

Simply setting:

   $form['#cache'] = ['max-age' => 0];

Resolved the issue.


Check path_alias_xt and subpathauto, I have used subpathauto to achieve this for nodes and path_alias_xt documentation says it does for taxonomy terms too.


Converting my project's requirements to drupal's concepts

I would do it as follows:
Create a vocabulary called 'VCR'
Add each manufacturer as a term, then each VCR category as a child of the manufacturer. So your taxonomy structure would be like this:

LG

FGX
Other Category

Sony

FGX
Some Other Category

Note that while FGX is the same term in both places, it will have a different Term ID.

You would then add this to your content type on the Edit Fields page. Select 'Term Reference' under the 'Field' column and 'Select List' under the 'Widget' column. There are other widget options but I think select list is correct in this case.

You would then proceed to install Views, its a contrib module. It basically allows you to list content in very customised ways. (There is more to it than that when used with Panels, another module that you may need.) Go to /admin/structure/views and enable the view named 'Taxonomy term'. This will allow you to override Drupals' default taxonomy display.

At this point going to /taxonomy/term/[int] (where int is one of the taxonomy terms' id) will display all content tagged with that term. You would use Pathauto and Token to create 'pretty' URL's, I would also recommend Global Redirect whenever aliasing content.

You may need to customise the View a little, because I cant remember offhand if it will list all content, including content that is a child term of the current term by default.

Views will allow you to make blocks listing content, and you can get a little fancy and use the core Statistics module to list the most viewed product. Panels is definitely worth investigating if you have time, but in my opinion keep it used sparingly.

Views also enables you to easily provide RSS feeds that people can subscribe to. I do believe it is possible to do email updates as well but it was a while ago on Drupal 6 and my memory is shocking. I think Simple News was what we used. In as I recall it requires some configuration but you could then send an automated digest every so often. Not exactly what you requested, but it may be possible to do it with Rules as you mentioned.

If you will be doing online sales I think Drupal Commerce would be your best bet though I haven't used it in production nor played with it for about 6 months or more.

As for the PS, I couldn't find any when I started Drupal, but to me the general rule so far has been: If it isn't an object, may be useful for sorting, or categorises anything in the real world then it belongs in a vocabulary as a term.


The .po file is not imported by being placed in the themes directory, you need to import it. To do that go here:

Home > Administration > Configuration > Region and Language > Import


Currently, exposed filters in Views in Drupal 8 don't use the new HTML5 elements.  Essentially, you get text inputs, selects, or checkboxes/radios.

There is an existing feature request to add this to Drupal 8.

I suspect you could form alter the exposed form to change the types.  This is untested, but essentially what the patch on that issue does:

function MYMODULE_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form['the_exposed_date_element']['#type'] = 'date';
}

That won't work for ranges, but it should give you a start.


So, without knowing more about your production and dev environments, it's hard to say.

Most people would probably advocate moving your codebase with GIT, rather than manually as FTP programs will usually not move files prefixed like your .htaccess file (which maybe causing your whitescreen). If you're going the manual route, I would rsync a copy of your production sites folder, zip it, and the move it to your local computer, install drupal from scratch, then move your files over, set up the db and settings.php for your local environment, run update.php, and profit.


How do I create a download link knowing the uploaded file ID?

First, load the file using file_load(FILE_ID) and get URI like below:

$file = file_load(1);
$uri = $file->uri;

After that generate link using file_create_url();

$url = file_create_url($uri);

Get file name also:

$filename  = $file->filename;

And finally, create a link using l().

l(t($filename), $url);

and output will be like picture-6.png


You can use variable_get() to get the site name, but you shouldn't use it directly in the template file or you could break caching.

Instead, define a preprocess function in your theme's template.php file:

function MYTHEME_preprocess_page(&$vars) {
  $vars['site_name'] = variable_get('site_name', 'Default');
}

Then you can use this in the template file:

Copyright © <?php echo date("Y"); ?> <?php echo $site_name; ?>

Before doing that, though, check whether you already have $site_name available in page.tpl.php. Some themes add it for you, some don't.


How to create view of referenced nodes with fields?

Adding node reference field to contextual filter and select "Provide a default argument" in it and select "Content ID from URL". This will do the needful.


How to create 10 extra nodes when a node of a specific content type is created?

You might experience an infinite loop here since every time you save the node (auto-generated or not), hook_node_insert() gets invoked. To prevent this infinite loop, you can use an extra pseudo-property in your hook_node_insert() to dictate if whether or not nodes should be automatically created.

Below is an example of how your hook_node_insert() might look like:

// If the node is an auto-generated node, don't create additional nodes.
if (!isset($node->auto_generated)) {
  // Auto-generate 10 nodes.
  for ($i = 0; $i < 10; $i++) {
    // Create a new node object and populate its fields.
    $node2 = new stdClass();
    $node2->language = LANGUAGE_NONE;
    $node2->type = "test";
    $node2->title = "Auto-generated (" . $node->nid . "-" . $i .")";

    $node2->created = REQUEST_TIME;
    $node2->uid = $node->uid;

    // A flag to let hook_nodeapi() implementations know that this is an automatically
    // generated node.
    $node2->auto_generated = TRUE;

    // Finally, save the node.
    node_save($node2);

    watchdog('test', "Auto-created node: <pre>@node</pre>", array(
      '@node' => print_r($node2, TRUE),
    ));
  }
}


Batch operations: callback_batch_operation() not invoked

Yes, it was stupidly obvious!

When bulding my $operations I wrote
$operations[] = array('multilang_default_process', $category);
while according to the batch_set() documentation it should be
$operations[] = array('multilang_default_process', array($category));

Sigh...


How to translate content of the composite element settings?

You need to create a schema config file to make them translatable.
I have done it like this by creating my_module.plugin.handler.schema.yml file in my my_module/config/schema directory.
webform.handler.my_element:
  type: mapping
  label: Booking email
  mapping:
    booking_email:
      label: 'Something'
      type: text


Redirect from "/mynode?language=de" to "/mynode" after storing the language in the cookie

You want to send them the language code in the url with the link as http://mysite.com/de/my-url-path and then make sure that you've enabled both session and url as detection methods at admin/config/regional/language/configure


Disabling access to admin pages during maintenance

Assuming that you are user 1, and that the contributing users all have a particular role; you should be able to just remove the administer site configuration permission from that user role whilst you're working.  This should disallow access whilst under maintenance mode.


No, you don't need to duplicate file, just go to /admin/config/regional/translate/translate and search for what you want to translate.

To be able to translate strings or variables from custom page.tpl.php file, all of them in the file need to be translatable, ie. to be in t() function, so if you can't find words that are from some custom .tpl.php file, make sure that particular string or variable in the file is translatable (in form like I mention).

For more information about using function t() look this.


validate and submit handlers are added to the corresponding form element, e.g. $form['actions']['submit']['#submit'][] = 'foo'.  and same for #validate.

Honestly no idea what those methods are used for, never used them. Maybe internally, during form processing.

Also note that the node form currently has multiple submit buttons (save as published, unpublished and so on), so you'd probably need to add your submit to all of those.


You're missing a closing </fieldset> tag which probably won't be helping things, but I wouldn't advise doing it the way you currently are anyway.

A better way would be to make use of the theme_fieldset() function like so:

// Make sure the collapsible library is loaded
drupal_add_library('system', 'drupal.collapse');

// Build up the fieldset
$fieldset = array(
  '#theme' => 'fieldset',
  '#title' => 'Viste aggiuntive',
  '#attributes' => array('class' => array('collapsible', 'collapsed')),
  '#description' => 'fieldset extra.',
  '#children' => '

Vista progetti

</fieldset>'
);

// Add it to the body
$body .= render($fieldset);

That works great for me.

You might want to replace the call to render() above with drupal_render() as it offers a minute performance increase; I tend to use render() for all my calls for this sort of thing for continuity, and so that I don't have to check the type of the data being passed.

In this case, as you know the argument is not a string, you could save yourself the few microseconds and use drupal_render() instead.


Remove the image style from node--type.tpl.php

I found it, in field.tpl.php.

$items[n]['#display_settings']['colorbox_node_style'] = "";


How should I configure cron tasks to make them automatically run on GoDaddy?

I don't have much experience with GoDaddy (I prefer BlueHost), but you could use the PoormansCron module instead of running it manually. Also, if you update to Drupal 7 this is included in core.


How to remove a role after a user adds a payment method in Commerce?

commerce doesn't offer the (content-)entity create event. You could use a hook ..

hook_ENTITY_TYPE_create -> after the entity was created 8will suit your need I guess)
hook_ENTITY_TYPE_presave -> before the entity will be created

Or setup events for entity creation, see Does Drupal 8 entities have any events I can listen to?


How to completely hide a table header in views?

Implement hook_preprocess_views_view_table(&$vars) in theme or custom module and set $vars['header'] to empty array. Template completely ignores thead when header variable is empty. For example:

function MY_THEME_preprocess_views_view_table(&$vars) {
  if ($vars['view']->name == "my_view") {
    $vars['header'] = array();
  }
}


hook_preprocess_page(): how to tell a views page?

views_get_page_view() finds out what, if any, page view is currently in use. If it returns NULL, then the current page is not a views' page.

But using drupal_add_js() and drupal_add_css() in a hook_preprocess_page() won't work as expected because the variable $script and $style variables have already been set by template_preprocess_page(). Views's template preprocessing (see Jeremy French's answer) is probably a better place to add your CSS and JavaScript.


it sounds like you want to modify the source contributed module :(.

You just write some custom CSS in your theme to target the item. In your theme.info file:

scripts[]=my_theme_overrides.js

Then in your javascript file you write the following, as an example (untested, should work, you may need to tweak it.):

/* in my_theme_overrides.js */
(function ($) {
  $("#how_to_become_a_grantee-block-0").removeAttr("tabindex");
})(jQuery);


Is there a distribution optimized for heavy data traffic?

You should have a look at Pressflow.

  Pressflow is a distribution of Drupal with integrated performance, scalability, availability, and testing enhancements.


How to get last_comment_timestamp for a node

It's in the node_comment_statistics table.


How can I disable the cache for a specific page or have the cache ignore query params?

After a lot of trying and retrying I settled on the following solution
function mythemename_preprocess_page(&$variables)
{
  if(isset($_SERVER['QUERY_STRING'])) {
    $params = \GuzzleHttp\Psr7\parse_query($_SERVER['QUERY_STRING']);
    if(isset($params['keys']) && strlen($params['keys']) > 0 && preg_match('#^/search#', $_SERVER['REQUEST_URI'])) {
      \Drupal::service('page_cache_kill_switch')->trigger();
    }
  }
}

As far as I can tell, this stops the cache from working if the request is on the search page and there is a query parameter present named keys


site created using drush arr failing with missing index.php

I think you problem is likely that you need to set the RewriteBase in the .htaccess file.  Edit your .htaccess, find the line that looks like

# RewriteBase /

And add a line under it that reads

RewriteBase /~drew/site2

then clear Drupal caches, and try your site.


Getting configurePhpcs is not callable after update drupal to 8.3.2

I assume, that after the Drupal core update, you've overwritten composer.json with your previous settings.

However, in Drupal 8.3.2, configurePhpcs has been deleted. This part of composer.json (around line 69 has to be changed:

"scripts": {
    "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
    "post-autoload-dump": [
        "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "Drupal\\Core\\Composer\\Composer::configurePhpcs"
    ],
    "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
    "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
},

You have to delete configurePhpcs line (and the comma at the end of the line above, so it should look like this:

"scripts": {
    "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
    "post-autoload-dump": [
        "Drupal\\Core\\Composer\\Composer::ensureHtaccess"
    ],
    "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
    "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
},

Then, you won't see the message anymore.


In both Drupal 6 and Drupal 7 files are not used independently. Most often, fields are used through a file field, on either a node (D6 or D&) or an entity (D7).

To do the above, I would suggest using a file field on something, that holds all the info about the file. You could add things like title, teaser  text, description in addition to tagging. For Drupal 6 the only option you have is to use nodes, for Drupal 7 you could use nodes or create your own entity in a custom module. The easiest thing will be to use nodes, as you wont need to create a lot of functions for editing, loading, rending... the entity. Nodes are probably also a good match in this case since the files are content on your site.

Another plus doing this, is that you would be able to use the Views module, and create different galleries or list of image files.


You first need to insert the file in the database, then assign it to your entity (a user in your case)

To insert file in the database say you have your file in a temp location. You can add it to the databse at the same time the file is moved to its final location:

// uid of user that to add the file.
$uid = $UID;

// Final file name
$filename = $FILENAME;

// Fieldname where to attach the file
$fieldname = $FIELDNAME;

// File temporary path.
$file_tmp_path = $FILE_TMP_PATH;

// Let's go!

// Load user object.
$account = user_load($uid);

// Gather file info.
$filesize  = filesize($file_tmp_path);
$mime_type = mime_content_type($file_tmp_path);

// Create file object.
$file = new stdClass;
$file->uid      = $uid;
$file->filename = <desired filename>;
$file->uri      = $file_tmp_path;
$file->filemime = $mime_type;
$file->filesize = $filesize;
$file->status   = FILE_STATUS_PERMANENT;

$destination .= '/' . $filename;

// Move to its final destination and add it to the database.
// file_move moves the file and is in charge of add the needed DB records.
$file = file_move($file, $destination, FILE_EXISTS_RENAME);

// Attach file to user.
$account->{$fieldname}[LANGUAGE_NONE][0]['fid'] = $file->fid;

$user_save($account);


Drupal Commerce: Can I have product list and checkout in the same page?

Try Commerce Express Checkout

  The Express Checkout button redirects to the Checkout page directly,
  without going to the Cart first, It also removes the Review page and
  adds the Payment checkout pane to the Checkout page, so the whole
  checkout process is done on one page.

Ckeck

http://www.drupalcommerce.org/discussions/952/all-checkout-steps-one-page
http://atendesigngroup.com/blog/express-checkout-drupal-commerce


Custom nested element and its child sub-elements callbacks

The whole workflow of form API is shown here  (source: https://www.drupal.org/node/165104).

You can notice that #process is top-bottom whereas #after_build is bottom-top, and #element_validate is a whole another step and bottom-top. You can also see that #value_callback is called quite early (even before #process).

Thus, and by experience, your #value_callback should not be more than 15 lines long, and in the case of a nested element, always take form_type_checkboxes_value or form_type_radios_value as examples: they only care about edge cases and rarely modify values.

This said, another input to take into consideration is the timeperiod module, because your way of handling will depend entirely of this module. (source: http://cgit.drupalcode.org/timeperiod/tree/timeperiod.module)

/**
 * Implements hook_element_info().
 */
function timeperiod_element_info() {
  // A duration form element which represents the duration in seconds.
  $types['timeperiod_select'] = array(
    '#input' => TRUE,
    '#tree' => TRUE,
    '#default_value' => 0,
    '#value_callback' => 'timeperiod_element_value',
    '#process' => array('timeperiod_element_process', 'ajax_process_form'),
    '#after_build' => array('timeperiod_element_after_build'),
    '#pre_render' => array('form_pre_render_conditional_form_element'),
    // Controls the available units. Array keys are the units, see
    // timeperiod_element_units(). The values control the number of available
    // values per unit, taking steps in the configured size starting from 0.
    '#units' => array(
      '3600' => array('max' => 23, 'step size' => 1),
      '60' => array('max' => 55, 'step size' => 5),
    ),
  );
  return $types;
}

timeperiod_element_value() does literally nothing (see its comment)
timeperiod_element_process() breaks down into units and sets up sub-elements
timeperiod_element_after_build() actually sets the
value

So based on these informations, you also need to implement #after_build, which is bottom-up, so it will run after timeperiod, and set the value using form_set_value()

Remember that validation is only for validation, and will always have processed values as input.


Normally the internal links /taxonomy/term/% are not used anymore, because all links Drupal puts on the page are aliased. If you want to prevent having multiple paths for the same page you can install https://www.drupal.org/project/redirect.
From the project page:

D8: Maintaining a canonical path and redirecting alternative URL's    like non-aliased path, path without language prefixes and so on
(Previously provided by Global redirect)


Can I make a Views "Rendered Node" field not be linked to the original node?

This happens because whenever Drupal renders a node someplace other than the node's page (for example, /node/12345) it will include the title as a link to the node itself. This is done in modules/node/node.tpl.php:

<?php if (!$page): ?>
  <h2<?php print $title_attributes; ?>>
  <a href="<?php print $node_url; ?>">
  <?php print $title; ?>

<?php endif; ?>

To stop this from happening in your view when using the rendered node as a field, you probably want to tweak the view field template. If you override node.tpl.php in your theme, other displays of nodes (for example, the default front page) will stop working as you expect.

I did this in views-view-field--test--rendered-entity.tpl.php using preg_replace:

$output = preg_replace('@(\s+
]*>\s+)]*>([^<>]*)(\s+
\s+)@', '$1$2$3', $output);
print $output;

Note that the exact regex will depend on the theme you're using. This is for an Omega subtheme.


How do I redirect user_view_page to user_profile_form?

I've solved this problem in the past with the Rules module.

Event:
User Account page is viewed

Condition:
User has role(s)

Action:
Page redirect
Parameter URL:[account:edit-url]

I created the rule and added the screenshot here: http://i.imgur.com/xjMPpIM.jpg

Here is also the exported rule:

{ "rules_test" : {
    "LABEL" : "test",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_view" : [] },
    "IF" : [
      { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "2" : "2" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "[account:edit-url]" } } ]
  }
}

I hope this helps!


Database Abstraction Layer and 'LOAD DATA INFILE' Statements

Your question is a little vague. I assume this isn't for a Content Type you created or an Entity in D7 ?!

As you pointed out this is DBMS specific. The drupal db api basically adheres to an ANSI SQL '97 (i think) specification. So you can do basic queries, updates, etc using the Drupal API. When you start talking about DBMS specific stuff you're outta luck.

The drupal API sits atop the PHP PDO library. This is an abstraction on top of many DBMSs as well -- you can do anything dbms specific with a bare PDO_Connection object ... called a stored procedure, or do your nifty INFILE usage above.

So you'd probably have to make your custom MYMODULE_form_submit() and do your custom query there from the raw pdo db connection. You can call Database::getConnection() in Drupal 7 to get the default db connection directly. Here is similar concept in calling a MySQL stored procedure from D7 asked here before on stackexchange.

Lastly, this isn't really drupal api related because you not seeking to call node_save() with your CSV data ... node_save() lives in the universe of the drupal API and has a succesion of function calls around it in the Drupal-verse, you're clearing asking for MySQL-verse stuff :)


How to re-order a mini-panel in a Panel generated page?

Okay, so I ended up finding my own answer while working on something else. I realized my scope was wrong, I was looking for an override page referring to a specific page type/section, but what ended up being the case was that there existed an override page for all nodes with unique content/layouts in use for each of them within the same area.

So there was ultimately a Panel Page doing the dirty deed as I had thought, but I was being too specific in where I assumed the changes were made, in part because I assumed an override page would have to maintain the same layout for all pages it overrides, but that's not the case I've learned.


Is there a way to manage a vocabulary with drag&drop when there are more than 100 terms?

Have you looked at taxonomy manager?

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


How can I list Drupal 8 Content Moderation draft

Out of the box, on Drupal, only users with the Bypass content access control permission can see every unpublished post, but that is a permission to give to a very small set of users, such as administrator users.
The other users can only see the unpublished nodes they created.

You can create a module that defines a new permission (e.g. View unpublished content), and implement hook_node_access_records_alter()/hook_node_grants_alter() to grant the view access to those users with the new permission.


In advanced section add a relationship by author like this :

Then add a field, choose User:name (the user or the author name) :

make sure that you have the relationship "author" in the field setting :

Now you should see the correct author name.


Since the bootstrap carousel is based on a content type, you should be overriding node.tpl.php instead. Try dropping a node--bootstrap_carousel.tpl.php into your theme and making your markup changes there.


How to use content type tokens File path in file and image field?

One way to do it, is to use File (Field) Paths, as node provides content type "subtokens" like:

[node:content-type:machine-name]

Problem with any other implementation will be caused by the fact that fields can be attached to things that does not have content types.

This answer is limited to nodes, so it's only a partial one, but it will do the trick in many cases.


Drupal 7 Date - Is there a way to change field settings if there is data in it already?

I got this working by doing the following without having to write any code. Keep in mind im only doing this for the DATE type fields:

example:

my old field: field_eventdate

my new field: field_placeholder

create the same field type with a different name and the options you want.
open up phpmyadmin
goto the table: field_config
search for the new field you created (field_placeholder)
click on the data column blob and download that.
search and edit field_eventdate and upload the file you downloaded which contains the new settings.
do the same exact thing for the table: field_config_instance
now we have to update the table structures of the field to encompass these changes. I first inspected the strucuture of the new field i created and see what the old table was missing. Once you have that down, create the missing columns in the old field that exists in the new field.
Do #8 again but this time for the revisions table. In my case it would be: field_revision_eventdate
delete the field_placeholder via the content type page as you wont need it anymore.

let me know if this worked for anyone else too.


search and facet api tables dropped during module updates

This issue is resolved, thanks to an insight rocketeerbkw provided about the drush up process. I changed my user umask setting to 022 in .bashrc to be more permissive for files that my account creates on the server. This completely resolved the database table dropping issue. Before I changed the umask, I had been running drush using my normal user account with a private umask setting, and when drush downloaded new files for updates, the resulting strict permissions broke any cache rebuilds that might have been involved and also on occasion broke the database connectivity. This was neither a MySQL nor drush issue.


User Locked out after 5 failed login attempts - how to help him?

If you use flood_unblock module you can just flush the flood for the specific user or ip.


Show markers on gmap from all nodes exposed in view

If you set up the map display as an attachment, you can set it to inherit the exposed filters that you've defined for your job listing. You'll get one set of exposed filters that controls both the listing and the map.

There may be some issues - see this blog post by someone solving what looks like the same problem.


Can't get workflow to show up on D7 Menus

Make sure your account has "Administer workflow" permission.


To save yourself access headaches:

Get credentials for the "user 1" account that has full Drupal access
Get database access or a copy of the most recent database
Get SSH Access to the production server

To audit the site once you get access:

Install http://drupal.org/project/hacked to make sure there haven't been any undocumented changes to Drupal core or contrib modules.
Look in /sites/all/modules/custom to find any custom modules. If nothing is there one good way to tell if you're missing any hidden ones is by looking at http://example.com/admin/build/modules and looking for modules without a version number. They may be hiding in /modules or /sites/*site_name*/modules.
Have a look at the theme and especially the contents of template.php. Often times a site will have a lot of modifications happening here.
After looking at the items found in #1, #2 and #3 you shouldn't expect to have found a whole lot. The custom modules should be mostly hook implementations and 'glue code' not re-inventing the wheel or re-creating functionality found in popular contrib modules but your mileage will vary here depending on how custom the site requirements originally were.


Can I use entityreference module with my custom entity to display it?

I figured this one out. Entityreference runs entity_access() before returning $items:

$items[$id][$delta]['access'] = entity_access('view', $field['settings']['target_type'], $target_entities[$item['target_id']]);

To get this working, you need to set the 'access callback' property in hook_entity_info(), which is an extended property that is checked by entity.module, not by core's entity functionality. So, for example:

<?php
return array('my_entity' => array(
  'label' => t('My Entity'),
  'controller class' => 'MyEntityController',
  'base table' => 'my_entity',
  'uri callback' => 'my_entity_uri',
  'load hook' => 'my_entity_load',
  'fieldable' => FALSE,
  'label callback' => 'my_entity_label',
  'access callback' => 'my_access_check',
  'entity keys' => array(
    'id' => 'id',
    'label' => 'name',
  ),
);

function my_access_check($op, $entity, $account, $entity_type) {
  // ...do something
  return TRUE;
}
?>


How to add a menu tab to a node to link to an information page to be used by author?

Check out the Examples for Developers module, particularly the menu_example sub-module. You are looking to create a MENU_LOCAL_TASK-type menu. This should get you started.


How to pass variables between preprocess functions

Hm...

First of all you should control order of preprocess functions execution.

preprocess_block executes earlier than preprocess_region, preprocess_region earlier than preprocess_node, and so on...

In first preprocess, you should declare static variable, like here.

$var = &drupal_static('variable_name_that_will_be_placed_in_static_stack');
if (!isset($var)) {
  $var = $value_to_store;
}

So, you can access this var from later executed functions.

$var = &drupal_static('variable_name_that_will_be_placed_in_static_stack');

As for your problem, it's more easy to get node from menu_router:

theme_preprocess_region(&$vars)
  $node = menu_get_object();
  if ($node) {
    // get required value
  }
}


Checked as default --> The user must confirm the account cancellation via e-mail.

Consider never modifying core or contrib modules.

Instead, the right practice here is to use hook_form_alter() or hook_form_FORM_ID_alter() in a custom module.

So, configure a little module and put the following code in it:

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  //get your form id
  drupal_set_message("Form ID is : " . $form_id);
  switch($form_id) {
    case 'MY FORM ID':
      $form['user_cancel_confirm']['#default_value'] = 1;
      break;
    case 'OTHER FORM ID':
      //do sthing
      break;
    //...
  }
}


How can I translate the label of a vocabulary?

It will be default by the current language.

There are only two ways to get something else, unfortunately:

a) Use ConfigEntityStorage::loadOverrideFree to load a config entity without overrides, then it is in the default language of that entity, which is what language() returns.

b) You can set the current config language and then load the entity. See for example user_mail function :

  <?php
  // Get the current language and override it.
  $language_manager = \Drupal::languageManager();
  $language = $language_manager->getLanguage($desired_langcode);
  $original_language = $language_manager->getConfigOverrideLanguage();
  $language_manager->setConfigOverrideLanguage($language);

  // Do your thing here.

  // Restore the config language.
  $language_manager->setConfigOverrideLanguage($original_language);


$file->original: Where does it come from?

$file->original is set from file_save() to make it available to hook_file_presave(), hook_entity_presave(), hook_file_insert(), hook_entity_insert(), hook_file_update(), and hook_entity_update(). It is then removed from file_save() before the function returns the file object to the caller.

// Load the stored entity, if any.
if (!empty($file->fid) && !isset($file->original)) {
  $file->original = entity_load_unchanged('file', $file->fid);
}

Clearly, if the file was not previously saved, $file->original doesn't get set.


301 redirects are considered the best way to handle redirected pages, for they inform search engines to update their databases with the new paths.
Edit your .htaccess file in a text editor. [Note: Be sure to save the file in "UTF-8" format.]

In the file, you will find the commands:

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on
  # Modify the RewriteBase if you are using Drupal in a subdirectory and
  # the rewrite rules are not working properly.
  #RewriteBase /drupal
RewriteBase /

Immediately after that code -- and before the Drupal-provided "Rewrite old-style URLs" commands -- add your rewrite rules using the following format:

#custom redirects
RewriteRule ^old/URL/path$ http://example.com/new/path [R=301,L]
#end custom redirects

For detailed discussion https://drupal.org/node/38960


how do i create a site that allows users to create "organizations?

The module to do this with in Drupal would be Organic Groups https://drupal.org/project/og. It's not a trivial module though. Here's the official documentation: https://drupal.org/node/1114858.

There are some online courses available from for example Lullabot: http://drupalize.me/series/organic-groups-drupal-7
and Brian Lewis: http://modulesunraveled.com/organic-groups-7x-2x.


Error: "module does not exist" after I removed a module from the file system without disabling and uninstalling it

@Leigh comment:

It's fairly straight forward - put the files back and then uninstall
it before deleting again

Solved the error


Proper debugging of REST Resource due to cache

As per @4k4 's suggestion, I'll try to put into and answer what he helped me figure out (though some details are still a bit murky).

When developing in a local environment, we can override the settings.php file with a settings.local.php file. In this local file, we can setup several settings regarding disabling Drupal's cache functionality.

At the time of writing, the instructions in this link were pretty straightforward and sufficient, but I would like to point out a few aspects that I felt weren't very explicit:

In my specific case, while developing custom REST Resources, both the response and the function of my resource were being cached. This is something I want to work like this in production. Although, for development, caching the function of my REST Resource meant that everytime I changed it, I had to clear the cache to allow for XDebug to see the changes in my Resource file. I overcame this by following the instructions in the Find cache bins section of the above link. Regarding my use case, I think the relevant cache bins should be the discovery and rest.
I think (though not sure), that having these bins not cached results in having to clear the cache if you add new discoverable code to your installation, ie, modules, REST resources, maybe themes. As these operations aren't as frequent in my case as the debugging procedure, it's a tradeoff I'm willing to make, but YMMV.
If you are using gitto version your code base, be sure to .gitignore the sites/default/settings.local.php file, otherwise it might end up in your production server, making it substantially slower.
I also tried following the procedure using Drupal Console as the link above suggested, but apparently since version 1.0.0-rc12 the drupal site:mode dev command isn't supported because it proved unstable. Maybe that will change soon.


how to get tinymce value in javascript?+ Drupal7

Try this I suppose this may help.

  tinyMCE.triggerSave();

  $('#textarea-selector-id).val();

i suppose that your text area would be inline:TRUE;
change the text area to a div this may work

or

var editor='textarea-selector-id';
var content =tinyMCE.activeEditor.getContent();
alert(content);


You can in views rewrite the result of any field, or trim most fields, but if there is some logic to what you want to remove you would need to do with with a preprocess hook in your theme. In this case it sounds like you need to do the latter. Something like this should do the trick:

function theme_preprocess_views_view_fields(&$vars) {
  if ($do_your_checks) {
    $vars['fields']['field_name'] = preg_replace(...) // Use regular expression to change title.
  }
}


Installing a New Site with Drush and Ansible

I found in a comment somewhere deep in the internet that there is a hidden -r option to specify the drupal root within a drush command.

The new play looks like this:

- name: Site Install with Drush
  command: |
    drush si standard --db-url=mysql://{{ mysql_username }}:{{ mysql_password }}@127.0.0.1:3306/{{ mysql_dbname }} --sites-subdir="domain.edu.{{ drupal_uri }}" --db-prefix="d_" -r /vagrant/d7core/ -y
    chdir=/vagrant/d7core/

Note, I also added the -y option, because it will count as an ansible error when it asks you to confirm that you want to DROP ALL ON db.

Because this was hidden functionality and it took me an hour and a half and it was a random comment somewhere that I found that in, I figured I'd make it an official SO question so anyone else looking to automate a workflow could hopefully find this faster.


How to tell the difference between multiple image_buttons on the same form?


Use Case : Registration of a Team for some event

What you just described can indeed be implemented in various ways but it really depends on how you have architectured your website. Here is how to do it using relation angway:
Use relation module
After installing relation, Create a relation type and name it something like is member of and it's reverse has member. The relation will be from user2user and with arity of 2.
I wouldn't suggest using any other configuration, such as using a single relation from leader to all members. Later it will cause you more pain.

The Membership
I don't know. How does your website work? how does one request to be member of a group? many of these concerns are addressed by OG already.

The registration workflow
Create another relationship registered at relation, from user to the entity type representing the event (the node if it is a node). Use the module rules_link or rules_pane. Create a rules component: register at event that takes two arguments: event node and registering user.
In this component you have to add:

Action: Create a list of any entity type.

name it rel_list.

Action: Add an item to list.

list:rel_list
item:node_event from component arg.

Action: Add an item to list

list:rel_list
item:registering_user from component arg.

Action: Create an entity

of_type:relation
of_bundle:registered_at

From your rules_link or rules_pane call this component and feed it current user and the corresponding node. The created relation entity is an indicator of membership, for leader only!

Add another component: Fetch team members, it's arg: leader user, it will provide: list of users->members. write a custom rule fetch team members and query all members using EntityFieldQuery or use the module efq_rules to fetch team members. for each queried user, use the above component to create the relation.

you definitely want to have rules_conditional installed.
Central Place for storing memberships.
Instead of a direct relationship from leader to team members you might want to have a node representing the team and create relations from this node to users. this way if you needed to change the leader it can be easily done with removing the is leader of relation and creating a new one to the new leader. But then, having this central entity, why not make it an organic group?
I usually choose relation when I need a fine grained control over memberships.


How to delete a module from the Modules menu?

The module uninstall page in Drupal 6 is at http://mysite.com/admin/build/modules/uninstall.

For Drupal 7 it's at http://mysite.com/admin/modules/uninstall.

Once you disable a module using the main modules page, visit the uninstall page and you'll be able to safely uninstall. After that it's just a matter of deleting the module folder from your server, and you won't see it in the module list any more.

Whatever you do, don't just delete the module folder without disabling/uninstalling it first, or you could easily wreck the site.


How can I notify an admin when a user is contacted?

In a custom module

hook_form_alter() yourForm.

Add custom submit handler, it will run alongside with your defaut submit

$form['#submit'][] = 'yourSubmitFunction';

Inside your custom submit handler use drupal_mail() or any other result you need

function yourSubmitFunction($form, &$form_state) {
  drupal_mail()
  ....
}

Note: the form_state array contains all the submited values.


Need to add a JS file into  using a custom module with custom twig template

You can attach custom tags to any render array from where it bubbles up into the HTML head. In the following sample I'm adding structured data when a certain block is viewed. $value then contains what's being printed between the opening and closing script tag.

/**
 * Implements hook_block_view_BASE_BLOCK_ID_alter().
 */
function MYMODULE_block_view_system_breadcrumb_block_alter(array &$build, BlockPluginInterface $block) {

  // Get JSON-LD.
  if ($json_ld = \Drupal::service('easy_breadcrumb.structured_data_json_ld')
    ->value()) {

    // Prepare script tag.
    $structured_data = [
      '#tag' => 'script',
      '#attributes' => ['type' => 'application/ld+json'],
      '#value' => $json_ld,
    ];

    // Add script tag.
    $build['#attached']['html_head'][] = [
      $structured_data,
      'easy_breadcrumb_structured_data_json_ld',
    ];
  }
}

I hope you get the idea how this can easily be adjusted to get your custom snippet into the head. You can keep your logic in hook_page_attachments_alter but then let it look more like in the following snippet. Maybe you don't even need any #value at all.

/**
 * Implements hook_page_attachments_alter().
 */
function MYMODULE_page_attachments_alter(array &$attachments) {

  if ($js_file_url = \Drupal::config('MYMODULE.settings')->get('url')) {

    // Prepare script tag.
    $my_script = [
      '#tag' => 'script',
      '#attributes' => ['src' => $js_file_url],
      '#value' => 'test',
    ];

    // Add script tag.
    $attachments['#attached']['html_head'][] = [
      $my_script,
      'MYMODULE_my_script',
    ];
  }
}


How do I write a behat test to go to user/UID/somewhere when I only know the username?

You could use Sub-pathauto which will allow you to use /user/username/somewhere instead.


Get data form into hook_node_insert / hook_node_update

The $node object will be populated with the data from the form, the way for form is defined.

You can do something like this

hook_form($node, &$form_state) {
  $form = array();

  $form['my_value'] = array(
    '#type' => 'textfield',
    'title' => t('Some title'),
    '#default_value' => isset($node->my_value) ? $node->my_value : '',
  );

  ....

  return $form;
}

Then get the value on the node object.

hook_insert($node) {
  $my_value = $node->my_value;
}


Adding priced options to products in Drupal Commerce

Oh and no - I didn't set the term reference field to unlimited values because I only want them to pick one value from the list

I believe that is the problem... either you make it unlimited; even though, you will use it once

OR leave it at 1, but don't use a loop, just add action (for Amount Value data selection use commerce-line-item:field-price:amount)


Check the user permissions. The anonymous role might have one too many permissions granting access, such as "Use the administration pages and help".

You aren't running any sort of caching setups that might be caching a logged in experience and displaying it for anonymous users are you?


Views exposed date filter using "Is between" doesn't include end date

I agree this implementation lacks some UX polishing.
The reason why that day is omitted in your case is because you're not including the time, so a time of 00:00:00 is assumed, which is the beginning of the day and most of that day's time will be excluded. The first day also assumes it, but because it's the beginning of the range it includes the whole day.
The solution is to use the time along with the date, and give clues to users to orientate them with using Placeholder example values and the Filter field Description:
Empty form:

After filling in:

You can come up with better UX Label and Description, I'm just demonstrating a good starting point.


What is the relationship between field_data_field_ and field_revision_ tables?

{field_data_[field_name]}

  Standard data storage for a field. It's recommended you use
  _field_sql_storage_tablename to get the name of this table.

  {field_revision_[field_name]}

  Standard revision storage for a field. It is recommended to use
  _field_sql_storage_revision_tablename to get the name of this table.

For more details


You can use javascript for this.

Each quicktab "A" tag has an ID something like quicktabs-tab-name-0 (replace name with the quicktab name you have given)

You can use some thing like the below code to get the current day of the week

var d = new Date();
var n = d.getDay();

this would return a number which would be something from 0 to 6 where 0 Represents Sunday and so on.

The active class is set to li tag with in which the a tag is placed.

So first we need to remove the active class from all the li with in quick tab this can be done with

$(".quicktabs-tabs li").removeClass('active');

Next we need to add the active class to the current day's tab for which you could do something like.

$('#quicktabs-tab-name-' + n).parent().addClass('active');
// n is the day number we got from the code above.

Next you need to enable the tab page for the corresponding tab for that you would do the following. The first one would add the hide class to all tab pages and the second code removes the hide class from the current div.

$('.quicktabs-tabpage').addClass('quicktabs-hide');
$('#quicktabs-tab-page-id-' + n).removeClass('quicktabs-hide');

That should do it.

Just make sure that the tabs are arranged form Sunday to Saturday. So that quicktab ids also get the same numbering. If you want a different order then you can offset the number accordingly by adding the offset value and then getting the reminder value of a division by 7.

So in effect the complete code would be

var d = new Date();
var n = d.getDay();
$(".quicktabs-tabs li").removeClass('active');
$('quicktabs-tab-name-' + n).parent().addClass('active');
$('.quicktabs-tabpage').addClass('quicktabs-hide');
$('#quicktabs-tab-page-id-' + n).removeClass('quicktabs-hide');

This would go inside the document ready function.


Add a class the the form element (tag) of the search block form

you can use the prefix and suffix tag
like

$variables['element']= ['#prefix' => '
',
                        '#suffix' => '
']


How to get Users Email address in an Rest Export View for auth users

Access to the user fields is controlled by \Drupal\user\UserAccessControlHandler::checkFieldAccess(). Which returns forbidden() for email except if it's the current user or the user has administer users permission (which you obviously don't want to grant your normal users).

That is called by \Drupal\Core\Entity\EntityAccessControlHandler::fieldAccess(), collects the default access and everything returned by hook_entity_field_access(). You can't directly overrrule a forbidden(), but you can implement hook_entity_field_access_alter() and replace the default access check with one that allows access.


Reaction after click on custom link inside views

Have a look at the Rules Link module. Some details from its project page:

  This module lets you create links which trigger arbitrary functionality with the help of Rules.

  Features:

  Attach the link to any entities.
  Show the link only for certain bundles.
  Narrow the entities on which the link will be shown using the visibility conditions.
  The links are usually displayed using Views.
  For entities that can be displayed, the links can be shown on node view.
  Supports an arbitrary number of additional Rules parameters for passing context via Views.
  3 types of links: Javascript, Normal and Confirmation form links.
  Use individual permissions for each link.

Some more details (from its README.txt):

  To create a new link go to admin/config/workflow/rules_links and click on "Add rules link". Enter the title of your link and set all the settings. After clicking on the "Save Rules Link" button, the module will generate a new And- and Rules-Set and their forms will be embedded into the rules link editing form.

  The And-Sets are called Visibility Conditions and will define when to render the links. The Rules set is the rule, that will be triggered on clicking the rule. Additionally Rules Links also generates access permission for each link, which you'll have to set in admin/people/permissions.

  The best way to display the links is currently using views. Rules Links link will create a Views field for each link, using the title of the link as title for the field. So if you have link for nodes with the delete 'Delete node', you'll find the Views field under name 'Content: Delete node'.

  Alternatively you can use render the links directly in the entities that can be displayed, using the option 'Show link in entity' in the Rules Links settings.

  Note that this will not work for links were the parameters have multiple
  paramaters.

  If you would like to render a link yourself in a theme or in a module, than use the function rules_link_render_link().

PS: I'm assuming this question is about D7.


how can I make view_slideshow module thumbnail pager scrollable?

Views Slideshow JCarousel will suits your problem description best . Before Installing it you need to have views and views slideshow  enabled.One extra work you need to do is to create two folders in sites/all/libraries folder

1) sites/all/libraries/jcarousel - download the .tar file from https://codeload.github.com/jsor/jcarousel/legacy.tar.gz/0.2.9 and extract here.

2) sites/all/libraries/jquery.cycle - save here the .js file you get form http://malsup.github.io/jquery.cycle.all.js link.

Now .

create a view of content of TEST (let here be the content type is TEST).
Select Format slide show and click settings . Now in Bottom Widget(you can select top widget also) check the pager checkbox.
It will ask all the requirements like Number of visible pager item and scroll items . Save it and you are done.


Drupal 2 blocks same form function with different output not working

I would suggest to prefix the form array with your product ID (I guess $product->pid or something like this) :

function my_module_block_form($form, &$formstate, $product) {
    $form[$product->pid]['submit_product] = array(
      '#type' => 'image_button',
      '#button_type' => 'submit',
      '#src' => base_path() . path_to_theme() . '/images/buy.gif',
    );
    $form[$product->pid]['product_name'] = array(
      '#type' => 'hidden',
      '#value' => $product->name,
    );
    return $form;
}

Then the fields shouldn't be overwritten.


Node edit page not showing up using page.tpl.php?

Make sure you have the setting 'Use the administration theme when editing or creating content' unchecked in you 'appearance' settings page. This would override your theme on the node edit pages causing your page.tpl.php file not to be used.


Problem translation of terms menu - Drupal 8.5.1 - Distribution VarBase

I solved it, going to admin/config/regional/content-language and check the box in Custom menu link and solve the problem.


I can think of two solutions. I will improve my solution a bit if you clarify exactly what the concept is behind the fixed node ID.

Solution 1: Custom field

Create a custom boolean field (working just like the node.sticky property).
Filter and sort your view by the boolean property.

The advantage of this approach is that the admin would be able to change the hard-coded default node you want to display by simply updating the custom field from the node form. Also, they would be able to specify more than one such forced-appearance nodes, which is good in certain cases.

Solution 2: Custom sort handler

You can write  a custom views sort handler and add an ORDER BY n.nid = 2410 DESC.
You will have to ensure that this sort is placed before the other sorts though.

BTW, as an additional suggestion, if you are using a hard-coded nid in logic, then make sure nobody can delete that node, otherwise you will have to change the relevant code every time someone deletes that node by mistake.

Hope this helps! Good luck.


Set default value of a custom field attached to a Media file image field

Drupal has the capability to dynamically set a default value for a field, but it is not exposed in the UI.

Each field instance can be set a 'default_value_function', which has the following signature:

function my_default_value_function($entity_type, $entity, $field, $instance, $langcode) {
  // Returns a standard field structure.
  return array(
    0 => array(
      // This can be different depending on the field type.
      'value' => 'myvalue',
    ),
  );
}

To set the default value function, either:

Modify the field structure exported by Features to add a 'default_value_function' in the 'field_instance' part (and revert the feature),
Do something like this (once):

$instance = field_info_instance($entity_type, $field_name, $bundle_name);
$instance['default_value_function'] = 'my_default_value_function';
field_update_instance($instance);


How to theming on webform field element in single twig file (for example webform--contact-us.twig.html?

Make sure that you are pointing on the right template and try this code :

{{ form.elements.YOUR_FIELD_NAME }}
example : {{form.elements.full_name}

you can check this link : https://www.drupal.org/project/webform/issues/2865940


Programmatically create a taxonomy and attach a field to it

Create them in the ui, export them to yaml using the single config export ui, put the yaml files in your_module/config/install - done


How to correctly get Form API single checkbox value variable from database?

You could use constants in place of string literals, sure, but that's not related to the issue you're having. That's simply a matter of converting the statement you already have to a boolean.

Which is as easy as:

$bool_enabled = variable_get('MY_SETTING_' . $form['#node_type']->type, 'disabled') == 'enabled';
$form['MY_SETTING']['#default_value'] = $bool_enabled;

Incidentally, the string "enabled" evaluates to TRUE in PHP, so it's not possible for it "not to work with enabled", it's just that 'disabled' also evaluates to TRUE, so you won't ever see a falsey value.

Personally I think the simplest solution is store the variable as an integer, 1 or 0. Then you can just assign it straight to the form element and let PHP's implicit integer -> boolean conversion take over. That's how all core (and contrib, that I've seen) modules handle it.


How to drush rsync and sql-sync on windows with Acquia-Dev?

0
down vote
favorite

Answer (just to share some hours of experience):

To get rsync and sql-sync to work on remote server using Windows (w/Aquia) it is necessary to make changes to 2 files filesystem.inc and SqlBase.php.

First delete cygdrive/ from $path = preg_replace('/cygdrive/(\w):/', '/${1}', str_replace('\', '/', $path)); in line 61 of filesystem.inc

and change drush_shell_exec('gzip -d %s', $input_file)

instead of

drush_shell_exec('gunzip %s', $input_file) in line 144 of SqlBase.php

Happy Syncing!


How to move D7 from /sites/sitename to /site/default?

Adjust the path where your public files are stored - here: admin/config/media/file-system (Configuration -> File system -> Public file system path) - also review the temporary directory.


Fetch fields of a block defined via content type programmatically

You are in the wrong entity. block is a config entity to configure where and how the block is displayed and which plugin is used to build the block.

The plugin can be a core, contrib or custom block class. In your case a core plugin, which fetches content from the database. The content is stored in the content entity block_content.

So the entity type to modify the fields of a custom block is block_content and you have to use this hook:

hook_block_content_view_alter(&$build, $block_content)


How to upload images via CKeditor 6.x - 1.3?

Have you tried IMCE it can be attached with a number of WYSIWYG editors like FCK Editor, CK Editor, Tiny MCE


Found two modules that might help with your issue:

Views Merge Rows - provides a way to combine rows with the same content in the specified fields.

OR

Views Fields Combine - Similar to the one above, but hasn't been updated since 2012.

Experiment and see which one works best. You may need to use Rewrite Option too.


When and where should I replace tokens on a custom path for metatag context?

The correct place to specify the replace data was in hook_tokens().  I did not follow the original tutorial correctly and thought since my tokens were not available I was in the wrong place.

I ended up specifying my tokens as the current-page type.  After I did that, they displayed and I can now use them for my metatags.

As a side note, I did discover you need to run cron after you make changes to hook_token_info().


How to delete lines from a table created by a custom module?

You will find an answer here.

Basically you can use Drupal's drupal_write_record() to let Drupal handle that.

Or you can run a SELECT query first and an UPDATE or INSERT based on SELECT's result.

EDIT:

Based on information gathered in comments, it seems that the "savingfactors" table has several columns and only one row. If the row is already present, with any value, then a simple UPDATE query is enough. Here's an example:

function savingsscore_admin_form_submit($form, &$form_state) {
  db_query("UPDATE {savingfactors} SET saving_age21 = '%s'", $form_state['values']['saving_age21']);
  drupal_set_message(t('Your form has been saved.'));
}

That way you overwrite only saving_age21 field, ignoring others.

You can do the same with any other field you want to save.

There's an initial requirement: the row must exist. You can manually create it with a db client software, or you can implement Drupal's hook_install() inside your module .install file.


Why doesn't adding results in hook_views_pre_render work?

Don't know what the deal was with hook_views_pre_render, but adding to the result array works fine in hook_views_post_execute, and accomplishes the same thing.


It appears Azure's docker container services, which App Services leverages, is the cause of the problem.

Two big pains with Azure's app service (as explained by Azure support):

First, the docker containers are spread out across multiple drives, and PHP/Drupal's nature in using file caching causes it to run slower than it should.

Second, setting PHP settings to setup xdebug for instance, were lost when the service was restart. A "feature" in Azure, the container since it's a PHP image, everything outside of the home directory gets reset. This could be fixed by using an empty container, but then I'd probably still have the first issue.

My solution was to spin up a VM in Azure and manage it there. Runs MUCH faster, more reasonably now.

THANK YOU ALL


Adding array of objects to javascript from PHP

You can pass an array to JS like this:

drupal_add_js(array('my_module' => array('events' => $events)), 'setting');

In javascript you can get the values like this:

Drupal.settings.my_module.events;


Make node/field text input format available to Views

It is possible to do this with Views 3 in Drupal 7:

Add the field you need the format of to the view (E.g. field_body)
In the configuration form for that field tick the 'Rewrite the output of this field' box
Put the '[field_name-format]' token into the box

It will render the raw name of the input format, instead of the value.


Looking for most reliable and compatible (with other Drupal modules) multiple photo uploader and gallery system in Drupal 6 and Drupal 7?

They use Media Library on Drupal garden but this is only for D7 and it's still in dev. You can also try Cincopa which is really interesting, it's for D6 but they are developping a D7 version


Yes it's possible only if you do it programatically for this. You can use hook_entity_presave() and update encrypted values while saving user. And while retrieving data/fields you can decrypt with the key that you used for encryption and show in profile view page. Example:

/**
 *
 * @param array $edit
 * @param type $account
 * @param type $category
 */
function example_user_presave(&$edit, $account, $category) {
  $name = $edit['name']; // Get value of field.
  $edit['name'] = encrypt($name); // Encrypt and save.
}

/**
 * Returns encrypted string
 */
function encrypt($pure_string) {
  $encryption_key = 'SECRET';
  $encrypted_string = openssl_encrypt($pure_string, "AES-128-ECB", $encryption_key);
  return $encrypted_string;
}

/**
 * Returns decrypted original string
 */
function decrypt($encrypted_string) {
  $encryption_key = 'SECRET';
  $decrypted_string = openssl_decrypt($encrypted_string, "AES-128-ECB", $encryption_key);
  return $decrypted_string;
}


how to add attributes of the parent taxonomy in the DOM?

You can add the relevant Taxonomy parent Field to your Views, make it display the term ID. This way you get that information available as a token.
You can hide that field with Exclude from display and position it above all the other fields, so you can use it as a token in all of them without worrying about the position.
Then edit the Style settings of your "Parent" field that you want to style and enable the Create a CSS class option. You can enter the token for your parent TID in there.
Since css classes can't start with numbers make sure to enter a safe start for the class, for example: myclass-{{ tid }}
To find the list of tokens you'll have to temporarily enable the option Rewrite results > Override the output of this field with custom text > Replacement patterns.
You may need to Customize field and label wrapper HTML and/or Use field template depending on your particular configuration and output to get the class to show up.

Alternatively, you can construct the output of your field on your own with the Override the output of this field with custom text and enter what you want the HTML to show:

{{ field_output }}


Display webform results data in a Google Chart

There is another Drupal charts module that provides support for webforms: http://drupal.org/project/fusioncharts

Fusionchart has a little sub-module called fusioncharts_webform


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; }


White Screen of Death, From Apache to Litespeed

You want to increase your memory_limit and max_execution_time in your php.ini file.

Here is a link that tells you more about that


I ended up getting this working by using a module called Form Block and just putting the block containing the node form in the content. For some reason I never figured out, just calling drupal_get_form on that node form just did not work, even with the right node module files included. So, hopefully someone else struggling with this will be able to learn from this question


How to set or get the triggering element upon submit a form using JQuery?

Submit buttons (and their names) are special for Drupal. I'm not sure how this changed in D8, but in D7, the submit button name was used (IIRC) to determine which one was clicked.

I would suggest adding the submit button, hiding it with CSS and triggering a .click() to the button instead of doing .submit() directly. You can then either get the checkbox value if that's enough, or use a hidden field and some JS to determine which checkbox triggered the submit event (last clicked checkbox).


Is it possible to change the field type in a node form afterwards?

The answer is: Yes! It is possible. All I did wrong when altering the form is that I changed the '#type' of the container instead of changing the type of the textfield itself. I had to go one level deeper:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'MYCONTENTTYPE_node_form') {
    // dpm($form);
    $form['field_MYFIELD'][LANGUAGE_NONE][0]['value']['#type'] = 'select';
    $form['field_MYFIELD'][LANGUAGE_NONE][0]['value']['#options'] = array(
      1 => 'Value 1',
      2 => 'Value 2',
      3 => 'Value 3'
    );
    // #select doesn't need #size and #maxlength
    unset($form['field_MYFIELD'][LANGUAGE_NONE][0]['value']['#size']);
    unset($form['field_MYFIELD'][LANGUAGE_NONE][0]['value']['#maxlength']);
  }
}


Why is the fivestar rating displaying/suggesting 4 out of 5 stars when no votes have been made?

Same problem here. I've made a workaround putting a class and set "display: none" in it.


"global" keyword does not work from within drush script

To solve it I had to add global $foo; before declaring $foo.

I suppose it relates to this: http://php.net/manual/en/language.variables.scope.php#98811


Safest and most straightforward way is to move js file to module's info file, and include it always. just make sure it works only on elements it should, and on all of them. For this you need appropriate classes.

Other way is to use ['#attached']['js'] of highest possible element, instead of calling drupal_add_js manually. if you will set script twice, you will override older instance, so no problem.

If, for reasons unknown to me, you decide you have to call drupal_add_js yourself, use drupal_static to make sure you didn't call it already. It will require least changes in existing code - and in my opinion is worst solution. But will work. Typical usage is:

$mycounter = &drupal_static(__FUNCTION__, 0);

That makes $mycounter shared among all scopes where it is called, and initialized to 0. Then, you can test if it's still 0, and if it is - add your JS and increment counter with good old $mycounter++


I applied this patch and now it works

http://drupal.org/node/1508994


Have a look at Disclaimer module; it seems to be the functionality you're looking for.


Get data from remote REST API (read only)

In case anyone else have the same problem. By replacing the name "Authorization" like this:

  $headers =  array('Notified-Custom-Token'=>'my-unique-token', 'Content-Type'=>'text/json' );

... it worked and I got a success response with code 200. My mistake was to believe that Authorization was a mandatory name in the name/value pair.


How to add a field to Views table output with hook_views_pre_render?

To take a different approach: you could add the field through the UI as normal, and use hook_views_query_alter() to change the join type:

function MYMODULE views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view' && $view->current_display == 'foo') {
    $query->table_queue['field_data_field_myfield']['join']->type = 'RIGHT';
  }
}

That should get you the same effect with a bit less effort.


Your callback must look like this
zoekproduct_zoek_getypte_text($form, &$form_state){}

check what values you receive in $form_state or $form


Views - user/role has access to edit node

Views accessed can be controlled by Views Access configuration, check the screen shots if it helps.

Step 1: Find the Views Access Configuration

Step 2 : Opt the permissions, which suit your needs

Step 3 : Configure the permissions


How can I save multiple (checkboxes) values in a configuration entity?

Config (schema) defines two basic types of complex/array definitions.

Mapping:
When you have limited, known set of keys, each with a specific type, e.g. a few strings, integers, booleans and so on.

Sequence:
When you have a unlimited list of values that all have the same type but with unknown or numeric keys. Each element must have the same type. The top level in a config entity and simple config is always a mapping (the type there is a config_object or config_entity or so, but those all extend from mapping)

In your example, you would define the user roles as type sequence in config schema, and as a standard php array in your config entity class.

You can also combine this in any way you can imagine, you have a mapping, one key is a list, each element is a mapping, and so on.


Administration Notifications this is a simple module that can be used for communication of site changes/updates between the site designer/developer, and the site owners.

  if you maintain a drupal installation for another company, you can use
  this module to inform them when you have updated versions of the site
  (ex drupal 7.1 -> 7.2), updated modules on the site (i.e.
  Administration Notifications 7.x-1.0 -> 7.x-1.1), added new modules,
  or changed the site design in some manner.

or you can try Activity module.

  The Activity module keeps track of the things people do on your site
  and provides mini-feeds of these activities in blocks, in a
  specialized table, and via RSS. The module is extensible so that any
  other module can integrate with it. The messages that are produced are
  customizable via the admin interface and are context sensitive.


Why did all my themes disappear when I upgraded to PHP 7?

I don't know specifically why your themes disappeared, but the requirements page for Drupal (https://www.drupal.org/docs/7/system-requirements/overview) states:

  Drupal 6: PHP 5.x only (5.2.5 or higher recommended). Warning: support
  for PHP 4.x has been dropped. Drupal core should work with PHP 5.3.x,
  but PHP 5.3.x and higher may produce errors or unexpected behavior
  especially for contributed modules and themes.

PHP 7 is definitely not supported. You will likely find many more errors than this over time.


Can I avoid creating a new revision of every attached field upon entity save?

I have looked around and found one HACKY solution. I think it probably has some serious side effects that you may be able to handle with custom code and db queries. This is definitely not a generic solution.
I did my test on the node entity and every thing worked fine in my 5 min test case. Here is what I did:

function playground_node_presave($node){
  dpm($node);
  // do a query here and check if the value is in the field_revision_table is
  // equal to the value on the node/entity object.
  unset($node->field_cookies);
  dpm($node);
  // The node will be saved without changing the value of the field and without creating
  // creating a new entry in the field_revision_table.
}


How can I add alphanumeric, numeric and email validate validation in my custom form?

You can use Form API Validation module for this.

It has Available Validators like "alpha_numeric" which accept only Alpha Numeric characters and for more see below image.

Just install the module and enable it in admin and then

For alphanumeric use:

'#rules' => array('alpha_numeric'),

For numeric use:

'#rules' => array('numeric'),

For email use:

'#rules' => array('email'),