Devel module has a submodule called Devel node access, it is really useful to evaluate and track permission problems on nodes. Enable it and place the blocks on a region you're using in your template.


Adding Theme Suggestions Programmatically For Views (Rows & Fields)

Your Solution is good, but there is a cleaner one. You can use the hook_theme_suggestions_HOOK_alter, so you do not have to check if it's a view or whatever you want to check.

In your case it would look like this:

    function spve_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
        // If you want you can add a template suggestion for all views
        // based on their ID:
        $suggestions[] = sprintf('views_view__%s', $variables['view']->id());

        // Or you can check the ID, add suggestions, do whatever you want
        // ...
    }

    function spve_theme_suggestions_views_view_field_alter(array &$suggestions, array $variables) {
        // Check here the id, add suggestions, do whatever you want
        // ...
    }

More informations in the Drupal Theme API


Set boolean (single on/off checkbox) value while creating a user

The help message for this field says: If left empty, "1" will be used and if left empty, "0" will be used. So I left this field blank and assumed you could programmatically set the value while creating a user. This doesn't work at all for me.

You actually have to explicitly define the On and Off values in order to be able to set them while creating a user.

Then you can set the value in the user object.

'field_user_account_terms' => array(
                'und' => array(
                    0 => array(
                        'value' =>  1,
                    ),
                ),
            ),


I want to change language in a select list and whole site changes to selected language(All content)

I don't believe you need Internationalization module, core's Locale module will already do the job. It makes content translatable, so yes you need to translate it manually. When you enable Locale and edit a node, the option to enter a translation will appear.


Drupal Commerce: How to theme Product Field

I have figured this out.

1) Create a file named:  node--NAME-OF-CONTENT-TYPE.tpl.php

2) Insert the following in the file:

<?php print render($content['field_product']); ?>
<?php print render($content['product:NAME-OF-FIELD-ATTACHED-TO-PRODUCT']); ?>

<?php print render($content['field_product']); ?> is the add to cart drop down menu, so if you put the fields below it, they will appear under the add to cart drop down menu.

3) Clear cahces (at YOURSITE.com/admin/config/development/performance)


Programmatically update an entity reference field

You need to use code similar to the following.

    $node = Node::load($nid);
    $node->field_code_used_by->target_id = $user_id;
    $node->save();

For a multiple-value field, to add the value to the end of the list, use the following code.

$node->field_code_used_by[] = ['target_id' => $user_id];

Another way is setting the entity property with the entity object, as in the following code.

    $node = Node::load($nid);
    $user = \Drupal\user\Entity\User::load(1);
    $node->field_code_used_by->entity = $user;
    $node->save();


Stop exposed filters from rewriting url to begin with taxonomy/term/all

Assuming Drupal 7.x and Views 3.x.

Edit the View. In the filter config, make sure the "Allow multiple selections" option is ticked. Without that, you've configured the filter to only allow a single option per filter.

If "country-animals" is setup as a contextual filter, you'll need a patch from this issue to allow multiple terms.

Hope that helps.


I used View tree Module to achieve this same kind of functionality but i used it for Node Reference. As per their module page, this module is also compatible for taxonomy.

Here are the steps to set Views Tree to display hierarchical taxonomy.

Create a new term view using the fields row style

add relationship for taxonomy term: parent term
add field term id (do not use relationship) and exclude it from display
add field term id with relationship, exclude from display
add any fields you want to display, like term name, term description, etc...
Change style plugin to Tree (Adjacency model)
Set Main field to Term ID
Set Parent field to Term ID with parent relationship


How to add a class to more link of a view?

You can do it by implementing template_preprocess_views_view() in your theme under THEMENAME.theme file as shown below:

/**
 * Implements template_preprocess_views_view()
 * @param array $vars
 */
function THEMENAME_preprocess_views_view(&$vars){
  if(YOUR CONDITION FOR ADDING A CLASS){
    $vars['more']['#options']['attributes']['class'] = array(
      ENTER YOUR CLASSES AS ARRAY ELEMENTS
    );
  }
}

Reference: http://www.drupalthemez.com/blog/d8-adding-class-more-link-view


How to add select years and months select Drupal 8.1 date picker?

From locating the core datepicker source code in core/modules/locale/locale.datepicker.js, I was able to inspect the $.datepicker object.

Then _defaults settings can be altered in a custom javascript fil as easy as:

(function ($) {
    Drupal.behaviors.alterDatePicker = {
        attach: function (context, settings) {
            $.datepicker._defaults.changeMonth = true;
            $.datepicker._defaults.changeYear = true;
        }
    };
})(jQuery);

All datepicker settings are documented here: http://api.jqueryui.com/datepicker/#option-changeMonth


How do i use a renderable array to create a list with children render arrays

I think what you are expecting is logical. But from the definition of theme_item_list() you can see that it expects value of the data key to be just HTML and hence prints it as it is. I could be wrong here and there is probably a hook_preprocess_* somewhere that pre-renders each item of the list.

Either way, an approach that should work is rendering your item before adding it to the list by calling drupal_render() yourself.

// .. your code .. //
$container_elem = array('#type' => 'container' ... );
$render = drupal_render($container_elem);
$row['item_list']['#items'][] = $render;
// .. your code .. //


Statistics module not effect with Services module

Statistics increments hits in hook_exit i.e:

statistics_exit

It's normally called as part of drupal_exit in drupal_page_footer

In any case, statistics_exit for the node counter actually checks

if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == NULL) {}

That won't be true on an api request URL.

You might need to implement

hook_services_request_postprocess_alter

check the node request and make the stats increment call yourself.

Something like:

/**
 * Alter results of the services call.
 *
 * @param $controller
 *   Controller definition
 * @param array $args
 *   Arguments passed to services callback
 * @param array $result
 *   Array of results that can be altered
 *
 * @see services_controller_execute()
 * @see services.runtime.inc
 */
function MODULE_services_request_postprocess_alter($controller, $args, &$result) {
  // Increment hit count for node view api requests.
  $nid = $result->nid; // May need to confirm this is the node id.
  if($controller['callback'] == '_node_resource_retrieve'){
    // See statistics_exit()
    if (variable_get('statistics_count_content_views', 0)) {
      // A node has been requested, so update the node's counters.
      db_merge('node_counter')->key(array('nid' => $nid))->fields(array(
        'daycount' => 1,
        'totalcount' => 1,
        'timestamp' => REQUEST_TIME,
      ))->expression('daycount', 'daycount + 1')->expression('totalcount', 'totalcount + 1')->execute();
    }
  }
}


How to set a default image on a Drupal 7 Media field

Whenever I need to do this I just use a plain old Image field and use the Media File Selector as the widget. That way you can specify a default image for the field and still use the nice popup media browser.

So far I haven't found any benefits to using a Multimedia Asset field type over an Image field type in this situation, but that's not to say there aren't any or won't be any in the future.

EDIT

At the code level the following might help you get started:

// Implement hook_field_info_alter to add a setting for the multimedia field type
function MYMODULE_field_info_alter(&$info) {
  $info['media']['settings'] = array(
    'default_asset' => NULL
  );
}

// Implement hook_field_settings_form on behalf of the media module
function media_field_settings_form($field, $instance, $has_data) {
  $settings = $field['settings'];
  $form['default_asset'] = array(
    '#type' => 'media',
    '#title' => 'Default Multimedia Asset',
    '#description' => 'The default asset to use when none is selected',
    '#default_value' => $settings['default_asset']
  );

  return $form;
}

That will add a default multimedia asset picker to the field settings. Then you just need to work out how to inject that default value into the field display when it's otherwise empty. I would guess at the use of something like hook_field_prepare_view() for this.

Note that there's no way to restrict the type of the default multimedia asset as those types are set at a per instance level, not at the field level. If you want to do it at the instance level much of the same code above will help but you'll have to extend it further to restrict the type of media based on the checkboxes on the instance form.


The easiest way would be within your code.

You could change your 'access callback' => TRUE, to a function e.g. 'access callback' => my_access_check,

And within that function you can have an if statement to detect if a 2nd arg existing and if it does return false which would provide an access denied

If you wanted to do a "page not found" or a redirect or something else then you could put this logic into your 'example_page1_callback' function


Error when attempting to create sync directory

Nothing wrong with that.

It is recommend to have the config folder outside of the public web folder; Drupal just doesn't have that. To keep the installation simple for non-experienced users, it puts that folder in the files folder, which has to be writable anyway.

Just create that folder and give Drupal write permission to it; you'll be fine.


How would I create conditional fields on install?

I ended up getting this to work by creating a feature for the node and copying the array to the module.

To get the 'ID' of the dependee and dependent, I used field_info_instance. After I had that I could pass that info to conditional_fields_dependency_insert.

I did all this in hook_install.


What kind of entry (or #type) should I insert to get just an custom
  html/text block between fields or above them all?

Item element type provides a display-only form element with an optional title and description.

$form['help'] = [
  '#type' => 'item',
  '#title' => t('Block title'),
  '#markup' => t('Block content'),
];

You may also add arbitrary content to render arrays using the #markup render array key as follows.

$form['text']['#markup'] = t('Some text.');


You can try installing DB Tuner and/or run mysqltuner.pl and experiment with the suggestions.

Edit to address the comments.

In addition to trying to optimize the database itself, you can also copy/paste the SQL that Views generates and run the query manually with an EXPLAIN.  This may shed some light on why the query is taking a while to run.  You can then edit the view as needed, and potentially add some indexes that the above tools may not have identified.


Use Colorbox instead:

Formatter: Colorbox
Content image style: Hide (do not display image)
Content image style for first image: Thumbnail
Colorbox image style: None (original image)
Gallery (image grouping): Per post gallery

Under 'multiple field settings' I set it to display 'all', choosing Display type: 'Simple separator' and changing this from ', ' to ' '.

https://www.drupal.org/node/1026112 #50


How do I use the mail manager without the $to value?

I would suggest that you avoid this approach as messages with lots of recipients in the bcc field are more likely to trigger spam filters on the receiving mail server.
I would loop through each email address and send them a separate email instead, if there are a lot of emails to send then consider moving them into a batch operation.


I've just tested the following code out locally and it "works", with the exception that when I view the submission results as an administrator, I see the original keys and not the keys that were altered when the form was displayed (which is what I would expect).

function my_custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_client_form_12') { // yours is different
    // 'options' is the component name for a multiple-checkbox component.
    $form['submitted']['options']['#options'] = array(
      1 => 'Foo',
      2 => 'Bar',
    );

    $form['#submit'][] = 'my_custom_submit';
  }
}

function my_custom_submit(&$form, &$form_state) {
  dpm($form_state);
}

dmp($form_state) showed me that the checkbox I had picked was indeed the one that was checked, and when I look in the database in webform_submitted_data I can see that the record  shows the proper value that I checked:

nid sid cid no data
12  12  2   0  2

where data = 2 shows the checkbox that I picked in my altered options (I picked "Bar").

Since the subsequent submission display is going to show the keys as they currently exist, it's showing me that I picked the original value for option #2. If I change that to "apples" in the component and then refresh the submission, it shows the 2nd option as "apples". So I could follow this up with another hook_webform_submission_render_alter() or hook_webform_submission_load() to change the options being displayed on submission view so as to be appropriate to who the user was that filled out the webform.

My suggestion would be to instead build your own form, since it sounds like you have more than one dynamic aspect for what you need, and store the data that will be dynamic as a serialized array in a 'data' column in your own table.


Double field may be used as key/value field.


Variable saved as string, not as integer

It probably has to do with how php handles POST values.

That is just generating a form element, which when the form is saved will get sent to the server as a string. Here's an attempt at phpfiddle to show you what's going on: http://phpfiddle.org/main/code/dmk-npy.

Basically you're either going to have to intercept the form submit and cast the variable to (int) there, or you'll need to cast it to an int when you're pulling the variable out.

Edit: Though I have no idea why your checkbox would be saving it as an integer.


hook_node_insert PDOException exception issue

You cannot call node_save($node) during hook_node_insert($node).

According to the documentation, that hook is invoked during the middle of the database transaction, so the node isn't committed to the database yet. So when you invoke node_save, the old node you're attempting to update doesn't exist yet, and it will attempt to create a new node (with the same ID). Thus, the collision.


How do I remove a character from the replacement pattern?

I'm not sure I completely understand your question. But I'm guessing this is what you're looking for.

In Views, under FIELDS, click on the name of your field
Click on REWRITE RESULTS
Enable Output this field as a link
In Link path, insert something like vehicles/[field_store_car_model], where
[field_store_car_model] is one of the available Replacement patterns.

Hope this helps.


Remove 'Switch to plain text editor' in CKEdtior

You do not need to use CSS. There is an option within the CKEditor profile.

Go to Configuration > Content Authoring > CKEditor then select edit next to the profile you want to effect. This way you can also limit this too certain users.

Then select editor appearance and scroll down to "Show the disable/enable rich text editor toggle" then select hide and save the profile.


How to avoid submitting a form when creating a new content, depending on some criteria?

You can add validation callbacks to any form in Drupal using the Form API. Specifically, you can use hook_form_alter to add a validation callback to the $form['#validate'] element.


Adding external databases to settings.php using prefix

If they're on the same mysql host (and you've got the appropriate permissions) you can access the tables by simply prefixing them with the schema name: otherdatabasename.tablename. You can even run queries joining across the two databases.

If they're on a different server you'll need to add a separate connection and specify it as part of the query by using the $options['target'] setting.


How to define content within a custom region?

Regions are nothing more than a block holders. To add content to a region, go to http://example.com/admin/structure/block (substitute example.com with your real domain of course), and just drag and drop slideshow block to "MyRegion" region.


Only downloading this module does not work. It has dependencies. You have not installed the required JS filed which required by module. Those all are dependencies and required by module to work properly. Here is the step wise procedure for installing Views slideshow properly for D8.

In the procedure steps, if you read 4th step it states that,

  Download the latest version of the jQuery Cycle plugin place it inside the jquery.cycle directory. The filename should be:
  jquery.cycle.all.js

This is just example, follow all the steps properly then only this module will work properly.


Why does this code work for the current term but not the parent term?

If you check out the docs for taxonomy_get_parents() you can see that the return value is an array of parent terms.

So you might loop through the results like this:

$parents = taxonomy_get_parents($current->tid);
foreach ($parents as $parent) {
  echo $parent->name;
}

or use just the first one like this:

$parents = taxonomy_get_parents($current->tid);
if ($parents) {
  echo $parents[0]->name;
}


Feeds: How to import images using Xpath Parser for XML?

Importing images into a multi-valued image field using image URLs from an XML file is not working for me. The debug output shows the image URLs being parsed correctly, but the images don't get imported.

The XML structure is:

             http://www.example.com/files/content/villa-102-1.jpg

             http://www.example.com/files/content/villa-102-2.jpg

The context is: //unit
The Xpath query for the image field is: unit_details/images/image/uri

I played around with the image grabber module for feeds, but it failed also.

I was able to import images using the CSV importer and the image URL, so this appears to be a problem with Xpath Parser, not Feeds.


How to access a field of a referenced entity in a computed field?

Only, you have to add a Condition (in 'Elements') to the rule of the class "Entity has field", and then a whole bunch of the referenced fields of the entity will appear and will be available.

You'll have to create another Component to call it and add it another Condition of "Entity has field" of the same bundle you want to access.


SimpleTest clicking one of multiple "Add Another Item" buttons

I think FileWidgetTestCase::testMultiValueWidget() should be useful as an example.

As you can see there, only drupalPostAJAX() supports to target the actual button based on the name, for drupalPost(), they actually mess with the HTML source ($buttons is a xpath result that can be altered).


AJAX event and disable select form element

try:

$form['select']['#attributes']['disabled'] = 'disabled';

Ok, a detailed explanation can be found on this article https://www.drupal.org/node/357328

But pretty much resumes to:

  we cannot simple set the $element['#disabled'] attribute of the
  element. The reason is this attribute is transformed into
  $element['#attributes']['disabled'] by
  _form_builder_handle_input_element executes()...


Drop-down Menus in Standard Drupal 7.4 Zen theme?

If you don't wNt to install other modules then your only option is to create the CSS / JavaScript needed for it in your theme.

If you don't want to use a module, take a look at nice_menus.


How to convert static HTML template to drupal theme

There is no such tool that converts HTML to Drupal theme. But there are services where we can create some kind of Drupal theme with basic regions & templates.

Some modules you can try

Themer 6.x only
Theme developer
Skinr

Theming Drupal 6 and 7

Modules for theming

A nice screencast for a beginner
Introduction to Theming Basics for Drupal 7


How to use select2 in form API drupal 7?

From what I recall, the select2 javascript needs to be #attached to a render node or otherwise included on the page, then the dom content loaded callback used to locate the HTML select items that should be modified. Something like:

function () {
  $('select').select2();
}

See https://select2.github.io/ for examples. Within Drupal, you should really use the Drupal 'behaviours' framework, so that the right thing happens when AJAX and other dynamic loading happens.

There is also the project https://www.drupal.org/project/select2 which may help!


How to create a line graph of the total user points on a profile page?

I realize this is an old post, but I wanted to add a workable solution for those that find this question when searching the topic.

I've been able to use a combination of the Charts module to create a view that display the history of the user's total userpoints.

It is fairly straight-forward to create a view that displays all of the userpoints transactions of a given user, however, I found the trickiest part to be display a 'running total' of a user's points.

The following recipe should help you create a view that charts the progression of a user's points over time.

Step 1: Download, enable the Charts module

Step 2: Create a view that Shows "Userpoints", and create a block view with the Chart display format. Screenshot below:

Step 3: Add the relationship Userpoints:User

Step 4: Add the following fields:

Userpoints Transactions: Timestamp
Userpoints Transactions: Points
Global: Math Expression

Step 5: Set the expression for the math expression field to: [expression] + [points_1]. You should also adjust the label for this field.

Step 6: In the chart settings, set the label to be the timestamp field and the data to be the math expression. Also, set the chart type to line.

Step 7: Add a sort criteria to sort by the timestamp field. Set the timestamp format to be Y-m-d.

Step 8: Add a contextual filter: User:uid to filter by logged-in user's uid.

You may want to create a page view to see the chart in action:


The correct and optimal way to check language and print field depending on language, without affecting performance

That's a reasonable way of implementing an alternative language switcher for specific field output.

To keep the logic out of the template, you could add it to hook_preprocess_node instead.

e.g:

/**
 * Implements hook_preprocess_node
 */
function MYTHEME_preprocess_node(&$variables){
  global $language;
  $lang_field_name = 'field_description_'. $language->language;
  if(!empty($variables[$lang_field_name])){
    $variables['description'] = render($variables[$lang_field_name]);
  }
}

Then you can just use print $description in the node--content-type.tpl.php file.

Make sure your cache is different for each language.

See also field_attach_preprocess for how field language translations are added in core.


Show related nodes of category selected in current node (using static select list)

I recommend converting your select list field to Taxonomy and use a module like Similar By Terms.

  This Drupal module attempts to provide context for content items by
  displaying a block with links to other similar content. Similarity is
  based on the taxonomy terms assigned to content. Blocks are available
  based on similarity within each of the defined vocabularies for a site
  as well as a block for similarity within all vocabularies.


Language cookie module not working in Safari?

I think you should further verify/tune your configuration at Configuration -> Languages -> detection and selection: the order you mentioned (= 'URL, Cookie, User') seems a bit strange to me. I.e. it'd be interesting to see what results you get by specifying "Cookie" BEFORE "URL" in your case.

Because with your current order, "Cookie" will only be used to select your preferred language if from the "URL" it's impossible to decide about which language should be shown. Though "User" is probably fine to leave it as the last one.


CiviCRM Profile form buttons showing but not linked in Drupal profile

Just a guess, but try opening the Advanced field set at the bottom of the Edit Profile Settings page, and deselect requiring creation of Drupal user account. You might get more responses if you posted more info on the fields in the profile, for example, what you expect to see.


First of all: welcome to Drupal :) But then I right away have say sorry, but I think it's not really a good idea to ask people to "guide you on how to…". People here try to ask straight questions and give straight answers – if they can.

About your actual question: for displaying a specific page as your front page a.f.a.i.k. all you have to do is to go to Configuration > then Site Information > then you can adjust the Default front page setting by entering the path of any of your pages… Hope this helps…?

And last but not least I can just recommend you spend some time with some basic recources and tutorials – for example Drupal 7 – the Essentials is sheer greatness! And the Community Documentation has almost every important aspect of Drupal listed, that one could need for a start…


D7 Views: Rewrite multiple field into one with custom separators

You could rewrite the output of the field with your comma (but without conditions), then exclude from display and use a global textfield to output the field again with your conditions, so if the field is empty it won't show the comma.


Reset password after creating user account programmatically

I guess you could utilize function user_pass_reset_url of user.module to generate reset link and send it via your custom _user_mail_notify function.

Generates a unique URL for a user to log in and reset their password.
Parameters
\Drupal\user\UserInterface $account: An object containing the user account.
array $options: (optional) A keyed array of settings. Supported options are:
langcode: A language code to be used when generating locale-sensitive URLs. If langcode is NULL the users preferred language is used.
Return value
string A unique URL that provides a one-time log in for the user, from which they can change their password.


image field - how to overwrite existing image?

Its not there -- this functionality has been discussed on Drupal.org and ruled out by the maintainer of the filefield module before because it could cause the original file to be deleted before the node is saved. You can follow their argument here:

http://drupal.org/node/427212

Fortunately, if you do want the file to be replaced when you upload a new one with the same name there is an alternate module you can add for 6x/7x called Upload File Replace that does this and avoids the issue above:

http://drupal.org/project/upload_replace


How to set a new taxonomy term without overwriting an existing one when using Rules?

The Rules Action Set a data value that your Rule uses, can only set 1 value, while you're trying to update something that is a list (or to use your own words: "...  set a new term without overwriting an existing one").

So try to replace your Rules Action (ie with the data_set) with an action "Add an item to a list". When doing so, you probably also want to set "ENFORCE UNIQUENESS" to true, so that you "only add the item to the list if it is not yet contained". Even though for your case it may not make a difference, IMO that is a kind of safety-belt when using this action.

For way more details about this, refer to "How to set multiple values to an unlimited Term Refence field with Rules". While reviewing this, also pay attention to the "Fetch entity by ID" (within the Rules loop): I wouldn't be surprised if you'd also need to add a similar "Fetch entity by ID".

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


View to display nodes with lat long in proximity of specific lat long

Geolocation Proximity seems to be exactly a solution for you. You will need to keep location data using Geolocation Field to benefit from it.

Current features are:

  Views filter that can be used to filter entities (nodes, users, etc.) based on distance from a certain point (defined as lat/lng point). The input widget is very basic at the moment. Patches welcome...
  Views field to display the calculated distance between the entity and a reference point (can be synced with filters' lat/lng values).
  User-friendly input widget for exposed filters using Google's reverse geocoder

Big lacking features are:

HTML 5 Geolocation input
proximity SQL look ups

It's competitor is Get Locations module. It's a suite that uses Google Maps API. One of it's functions is:

  Getlocations Search which uses Google Geocoding on entered search terms and shows nearby locations. The search form is fully configurable with options for setting the Search distance, Distance units, Number of locations to show and Restrict the search to a content type.

Emphasis mine.

Last but not least, you can use Computed Field. It can be calculated on access, so it is perfectly possible to make PHP computed field displaying "distance from X" where X is defined on the fly. You will need to write computation in PHP, but you will not be tied to any particular metric.


Theme taxonomy term page with template override

You can use the below filename structure to create a taxonomy term template:

taxonomy-term--[vocabulary-machine-name|tid].tpl.php


JavaScript running before page fully loaded

Drupal attach behaviors get called from a jQuery ready() callback upon initial page load (it is a little more complicated than that, though).  This means that the DOM is ready, but replaced elements may not be done loading.  Images are considered replaced elements, so your have a loading bug.

I get around these by using something like imageloaded, or manually attaching via $(window).bind('load', ...);, which will run when the whole page is done loading (including images).


Okay I think this might be what you're looking for:
http://api.drupal.org/api/drupal/modules!field!field.api.php/function/hook_field_display_alter/7

I'd throw that function on your template.php, enable the Devel module, then use kpr() to print the variables to the screen and go from there.


How to set up salt hash while installing Drupal 7?

I talk a bit about the new salts in my article on Improvements to Security in Drupal 7 which may help answer these questions.

Depending on when you need the salt you might be able to use drupal_get_hash_salt or you may be able to leverage the code it uses to create your hash.

Can you expand on "extend this salting concept" ?  What kind of extension do you want to do?

Salting is a standard part of hashing. You can read about salting on the php hashing pages. Changing your salt after the site is live may cause some problems in specific areas. My guess is that it depends on which modules you have installed and which features you are using. The one-time-login links are likely to stop working, but I'm not sure of other specific functionality that would stop.


Accessing Drupal database for read purposes

If you want easily importable data, consider using Views data export:

  This module is designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:

  CSV
  Microsoft XLS
  Microsoft DOC
  Basic TXT
  XML

You can import CSV or XML to pretty much any data analysis tool you may need.


How to make sticky articles show up first in a list of articles?

Enable of the "sticky" option within publishing options (for 1 or more nodes) is only part of the solution: within the "Sort criteria" of your view, you also have to add  "Node: Sticky" as your primary sort criterium (using the Views UI).

When adding this sort criterium to your view, you'll also see "...To list sticky nodes first, set this to descending." (which is what you seem to be looking for).


Is there a way to return "Drupal root" value that is faster than running drush status?

cd /path/to/drupalroot/sites/default
drush drupal-directory '%root'

On the old system I'm on right now, that clocks in at 3.5s, vs. 11.8s for drush status

If you are using site aliases, as tenken suggested, then you can do this:

drush sa --format=csv --fields=root


Why not just add a redirect in .htaccess or similar, e.g.?

RewriteRule ^sitemap.xml$ /en/sitemap.xml [R=301,L,QSA]


Drush How to sync between local and server?

what your looking to learn to do is called drush aliases.

You can read this: https://drupal.org/node/670460

And here are some examples of it: http://deeson-online.co.uk/labs/drupal-drush-aliases-and-how-use-them

I would suggest you to use a virtualbox installation of drupal to test this out so you can get familiar with it first by setting this up: https://drupal.org/project/quickstart

My main local environment for developing drupal sites resides in the virtualbox quickstart. From there I do my tests and you can sync to your live environments using drush aliases. You can test syncing just using the local sites first.


Change "Public file system path" with Amazon S3

You are looking for the following module: AmazonS3.


Notice: Trying to get property 'nid' of non-object

You will need to check if the $node variable is actually an instance of node object.

if ($node instanceof \Drupal\node\NodeInterface) {
  // You can get nid and anything else you need from the node object.
  $nid = $node->id();
}

See

How do I get the current node ID?


How to set form element order with field_attach_form (and why does it do it?)

I can't really offer much explanation here but here's my solution. I suspect it has something to do with having a single form create two entities and how you need to separate that to allow both to be created.

The above created both, but didn't order the form correctly. The solution below does both.

The solution came from bundling up everything to do with user registration and attaching it inside a form container as opposed to just putting it in the form.

As I mentioned in the question, the documentation says this function always attaches to the top of the form, so you position the form container at the bottom then put it in that.

Here are the updated sections of my code, only two sections changed, the rest stayed the same. So you can just add the following parts to the code above.

   ....

   $form['account'] = array(
     '#type'   => 'container',
     '#weight' => 61,
   );

   //The new form container I added is below

   $form['user_reg'] = array(
     '#type'   => 'container',
     '#weight' => 62,
   );

   ....
   //added variables for clearer reading
   $account = $form['#user'];

   //The crucial part is the third parameter. This attaches it to a container rather
   //than the standalone form
   field_attach_form('user', $account, $form['user_reg'], $form_state, $langcode);


How can $build['#attached']['drupalSettings'] change from hook_node_view to javascript?

I had strongly suspected a caching issue while ignoring something more obvious, that the hook was being called several times and passing the value of the last time it's called to the javascript. Just added a check to make sure it's passing the correct value and it solved the issue.


After calling drupal_flush_all_caches, menu items with access callback TRUE are giving access denied error

The answer lies in some custom code I wrote to understand why some unrelated things were issuing an error. I discovered it was this when I was copying the code to my test site and then putting in this new code which resulted in the same issue on the test site. So that is how I was able to narrow it down. Going forward, I am going to have 3 sites, one for new development, one that mirrors the live site, and the actual live site. The issue comes from being in the middle of upgrading modules on the test site and so I couldn't really use it reliably to test new code, so I would code it on the live site (a big NO-NO and I really shouldn't have done this). The only reason I didn't my custom code was an issue was because I hadn't cleared the cache in a while, so the menu items were still available.

Maybe this will help someone in there processes to not be dumb like I was.


how long do files hang around in temporary://?

Temporary files that are created with the managed file functions are deleted when they are older than six hours, and during cron tasks.

The description for the FILE_STATUS_PERMANENT reports the following text:

  Temporary files older than DRUPAL_MAXIMUM_TEMP_FILE_AGE will be removed during cron runs, but permanent files will not be removed during the file garbage collection process.

The value of DRUPAL_MAXIMUM_TEMP_FILE_AGE is 21600 (seconds), which means six hours.


Drupal 7 special chars not working in db_select

It doesn't look like anything wrong with query. I'm using drupal 7 with basic setup and one node(nid=3) has 24/7 in title & body and one node(nid=4) has only in body.

  // Make sure to decode, if the search string is part of URL.
  // $search_text = urldecode($_GET['query']);

  $search_text = '24/7';
  $query = db_select('node', 'n');
  $query->join('field_data_body', 'b', 'b.entity_id=n.nid');
  $query->fields('n', array('nid'))
    ->condition(db_or()
    ->condition('n.title', '%' . db_like($search_text) . '%', 'LIKE')
    ->condition('b.body_value', '%' . db_like($search_text) . '%', 'LIKE')
  );
  $result = $query->execute()->fetchAll();
  print_r(db_like($search_text));
  print_r($query->arguments());
  print_r($result);

and the result is:

// print_r(db_like($search_text));
24/7

// print_r($query->arguments());
Array
(
    [:db_condition_placeholder_0] => %24/7%
    [:db_condition_placeholder_1] => %24/7%
)

// print_r($result);
Array
(
    [0] => stdClass Object
        (
            [nid] => 2
        )

    [1] => stdClass Object
        (
            [nid] => 3
        )

)

Note: If you are getting the search string from URL as query string make sure, you have done urldecode() before send to SQL.


Replacing Private message module with nodes

If by API you mean documentation, there is a documentation for the module in the following link: https://www.drupal.org/documentation/modules/privatemsg
For actual API file: https://cgit.drupalcode.org/privatemsg/tree/privatemsg.api.php?h=7.x-1.x
In the same code repository, the module contains views folder with views integration, so I don't understand what you mean by no views integration?
And here is an example on how to theme the new messages block, you should check this file for more theming functions.
Hope that helps.


How can 'programatically' configure my site?

So You Want to Build a Drupal Distro

Take a look at Packaging a distribution on Drupal.org

Here are the steps:

Assemble the pre-requisites
Create a Drush Make file
Convert to a Drupal.org-specific Drush Make file
Build and verify it works
Commit your code to Git
Release your code on Drupal.org
Maintain your distribution

Another great tutorial How to Write a Drupal 7 Installation Profile

Also there is Profiler Builder module.

  Profiler Builder is a module for automating the creation of
  installation profiles and distributions. It has support for the
  Profiler installation profile simplifier library but is able to run
  independent of it (1.0-RC4+). This module creates a downloadable tar
  package that gives you a well made installation profile and associated
  drush make file based on the site its installed on.


How can I tell which site uses which database?

Big giveaways will be in the variable table, especially the two rows with the names:

site_mail
site_name

As hopefully these are different for each one of your sites.

Perhaps this database query can help you:

SELECT * from variable WHERE name LIKE 'site_%';


There are many ways to do it. Easy one is to add it on your theme's .info file: scripts[] = js/your_jquery_plugin.js
But then its everywhere.

You can add it in a block. Check that your text-filter is set to PHP (May need to be active in the modules: PHP filter). Then add drupal_add_js()


Failing to uninstall a module because "The website encountered an unexpected error. Please try again later."

The uninstall & updated errors are like symptoms of the same problem; your profile module installation has corrupted DB storage so the module can't remove its DB tables, or retrieve its entity definitions to upgrade it.
You'll need to do a manual recovery on in a test environment so you can fully uninstall then reinstall so it has functional DB schema again. Manually restore the profile table (or any other DB schema) that the modules needs, then attempt uninstalling again. Repeat this process so you're able to successfully uninstall the module, then re-install it so it has a functional schema.
Once you've confirmed the process works, perform it on your live DB (after backing it up).


How to correct my rule to prevent duplicate taxonomy terms to be created?

I think the Rules condition, URL Alias Exists is perfect for this scenario if put into two rules, one for yes and one for no. Taxonomy terms will have an alias once created so it's easy to check if /taxonomy_vocabulary/[A][B] exists before doing anything with C.

When the node is created or updated, the rules check for A and B added together to see if that AB taxonomy term already exists since every taxonomy term has an alias. If it already exists (yes), the rule fetches it and uses it and if not (no), it creates it.

For example, the first time a node is created or updated with A: New and B: York, "/cities/newyork" wouldn't exist so we create it. The next time we use A: New and B: York, the rule finds the existing term and fetches it.

The below assumes a single-language taxonomy vocabulary. The nodes can be multi-lingual.

PSUEDO-RULES

Rule 1 - Taxonomy C exists
Events: Node is saved / Node is updated
Condition: URL Alias Exists > Use replacement patterns to join A and B in Value field
              eg. taxonomy/[a][b]
Action: Create variable > [a][b]
Action: Fetch Entity by Property > Taxonomy Term > Name > Created Variable
Action: Set Data Value > C: Fetched Entity:0

Rule 2 - Taxonomy C doesn't exist yet
Events: Node is saved / Node is updated
Condition: NOT URL Alias Exists > Use replacement patterns to join A and B in Value field
Action: Create entity > Taxonomy Term > "AB" using replacement patterns
              (not the drop-down list!)
Action: Set Data Value > C: Created Entity

Rules exports
To test these rules, you'll need a Drupal install with Articles, Tags and no Pathauto messing with the urls.
Add three term reference fields to Article for the Tags Vocabulary.

Machine Names
field_tax_tags_a
field_tax_tags_b
field_tax_tags_c

Rule 1 - AB Term exists so fetch it

{ "rules_exists" : {
    "LABEL" : "Exists",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "path" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" },
      "node_update--article" : { "bundle" : "article" }
    },
    "IF" : [
      { "path_alias_exists" : { "alias" : "tags\/[node:field-tax-tags-a][node:field-tax-tags-b]" } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : "[node:field-tax-tags-a][node:field-tax-tags-b]"
          },
          "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "taxonomy_term",
            "property" : "name",
            "value" : [ "variable-added" ],
            "limit" : "1"
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "data_set" : { "data" : [ "node:field-tax-tags-c" ], "value" : [ "entity-fetched:0" ] } }
    ]
  }
}

Rule 2 - AB Term doesn't exist so create it

{ "rules_doesn_t_exist" : {
    "LABEL" : "Doesn\u0027t exist",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "path" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" },
      "node_update--article" : { "bundle" : "article" }
    },
    "IF" : [
      { "NOT path_alias_exists" : { "alias" : "tags\/[node:field-tax-tags-a][node:field-tax-tags-b]" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "taxonomy_term",
            "param_name" : "[node:field-tax-tags-a][node:field-tax-tags-b]",
            "param_vocabulary" : "tags"
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : { "data" : [ "node:field-tax-tags-c" ], "value" : [ "entity-created" ] } }
    ]
  }
}

After that, create and edit some articles only using A and B. C matches and instead of duplicating, will fetch the existing term.


Install drupal console and then try to install the site using drupal console

https://drupalconsole.com/articles/how-to-install-drupal-console

drupal si


This is not the solution I want, it is temporary:
In the UI, I created a select field with key medical_area
then with my alter function, it just override the webform and stored it there.
What I want:
Without having to create a select field in the UI, to be able to create a field through the alter function.


Block with articles from the same author

Don't use Content Titolo use Contenuto: Identificativo uid dell'autore

and use the following settings


How to make a user not being able to publish his content?

How about [implementing hook_node_presave($node)][1] in your custom module,so as example code consider the following

function mymodulename_node_presave($node) {
  global $user;
  // check if user has role and checking node->original is not set ensures it works only when insertion of node happens not when it is edited
  if (in_array("your_user_role",$user->roles) && (!isset($node->original))) {
    // keep the node unpublished
    $node->status = 0;
  }
}


Create a pager with "Yesterday", "Monday", "Sunday" etc

Contextual range filter module ( https://drupal.org/project/contextual_range_filter ) seems to be the most suitable option as per the above requirement, or you can try the views day of week module ( https://drupal.org/project/views_dow ).

I have created a view for day archive by using the contextual filter of view (without using the above modules) as below below:

but as your requirement seems to be creating a archive on the basis of week day therefore the best would be to use the above(Contextual range filter module, or the view day of week module), and than you can found the filter in the contextual filter of your view.


how to show contents tagged under a parent taxonomy term

I believe you may need to have the content tagged in both terms,  "Events" and "Type" for this to work without custom coding.

You can get this through a view or custom module quite easily, though. If no answers posted later on, I will post you an update when I get home as I am writing this from mobile.

Good-luck


Twig add attribute with value in a variable

I'm pretty sure the nested braces here are an error - inside a {{ }} expression, variables don't need to be enclosed again:

 {{ attributes.setAttribute('src', {{ rows[0].content }} ) }}

But for the real answer: This template isn't the culprit - the content is already rendered separately, passing through its own template which adds the comments.

See Get Views field value in Twig template, where the recommended way of getting at the unrendered field value is via the _entity object.


what if you try to call directly the Syntax Highlighter or Geshi libraries to be readed from view templates? here is an example of Geshi (http://qbnz.com/highlighter/geshi-doc.html#basic-usage) and here another with Syntax Highlighter (http://alexgorbatchev.com/SyntaxHighlighter/manual/demo/) Is only a suggestion (not tried).


You can use hook_mail_alter to customize the From:

MODULE_NAME_mail_alter($key, &$message, $params) {

  switch ($key) {
    case 'my_email_key':
      $message['headers']['From'] = 'My Email Name <my_email@address.com>';
      break;
  }
}


Display list of user name with user points sorted by points based on certain time period?

In the contextual filter of the view add Userpoints Transactions:
User
In views fields add Userpoints Transactions: Timestamp. I see that you do not want to display date in views, so mark it as Exclude from display.
In grouping setting of your view select Userpoints Transactions: Timestamp


GMAP Module map not showing markers after updates with js error: Clusterer is not defined

So, it's actually a rookie mistake. Updating the module wipes out all the third party js files you download. took me longer than it should to figure this out.


How can I programmatically insert date field values?

If your field's name is field_date you should access it by using

$node->field_date['und'][0]['value'] = $datetime_value;

And if it has an "end" date you have to set its value2 property.

Try to install devel, create a node for the content type you want to use and go to the devel tab node/123/devel to explore its object.


\Drupal::database()->select with Expression used as Condition

// Where Expressions
    $query->where('WEEK(sd.field_start_date_value) = :weekNo', array(':weekNo' => $weekNo));
    $query->where('WEEK(sd.field_start_date_value) = :weekYr', array(':weekYr' => $weekYr));

Apparently this can be achieved with $query->where();


What date format is this? Or is it even a date?

Those are dates stored as Unix timestamps, which are essentially the number of seconds since midnight, January 1st, 1970 UTC (the epoch is 1970-01-01T00:00:00+00:00).

As far as Drupal is concerned, they are proper fields on those entities, either TimestampItem, CreatedItem, or ChangedItem fields.

Keep in mind that the timestamp always refers to that epoch and always is referenced to UTC; there is no real thing as a Unix timestamp in a local time zone.  When working with them in Drupal it is always best to use DrupalDateTime objects, and use it methods for computation (which will inherit from \DateTime).


Views custom field select list like views custom field

This is very easy to achieve but does not do much on it's own :

Create a new field for something like Content:NID
Go to Theme Information in the view settings
Find the template fie name suggested for your field
Create that file in your theme folder eg views-view-field--my-view--page--title.tpl.php
Press rescan templates in theme information (file name will go bold)
Add the following to the file

<select name="ops_<?php print $row->nid; ?>">
  <option value="edit">edit</option>
  <option value="delete">delete</option>
</select>

It doesn't do anything on it's own, you could wrap it in a <form> and specify a path as your method to process it, or use jQuery to do something.

But ... There is also an excellent module called View Bulk Operations (VBO) which will probably give you all the functionality you need.


Implement boolean search in apache solr search

Here is a basic example of adding an extra parameter to the search query using the hook_apachesolr_query_alter()

/**
 * Implements hook_altersolr_apachesolr_query_alter().
 */
function mymodule_altersolr_apachesolr_query_alter($query) {
  $query->addParam('fq', 'my_field:(value)');
}

Check this page for more possibilities on altering the search query: http://drupalcontrib.org/api/drupal/contributions%21apachesolr%21apachesolr.interface.inc/interface/DrupalSolrQueryInterface/7


You can hide it dynamically if no products in the order are
shippable. We are using ubercart 7.x-3.4 and on the Checkout
settings page /admin/store/settings/checkout (Home » Administration
» Store » Configuration » Checkout) there is an checkbox 'Hide
delivery information when carts have no shippable items.' Then, when
you edit each product, the Product information vertical tab contains
a checkbox 'Product is shippable.'
You can hide it completely on the Checkout settings page /admin/store/settings/checkout (Home » Administration » Store »
Configuration » Checkout) there is a list of the panes available on
the Checkout. If you uncheck 'Delivery information' and 'Delivery method' those panes will never appear.  If you are going to hide the Delivery information pane then the other option on the Checkout settings page 'Use the same address for billing and delivery by default.' would be useful too.


User is notified when new content is created using Rules

It really depends on your setup. A simple way to achieve this would be to assign business users with a role let's say "Business". Once that's done you can create a trigger on creation of new node, set conditions based on your requirement e.g. user role = "Business" and category = "Plumber" and action to send out an email.

You might need additional modules if you're looking at sending out HTML emails.

Let me know if you need any help.

Thanks


This is not a complete solution, but can help.

If you want to look at something but dont want to spend the time investigating your site's aversion to the devel module, then drupal core's watchdog call can be helpful.  Also, I am assuming you have dblog or weblog module enabled to catch the error messages.  To make it more readable, like a krumo output, I often add my Explain function to a custom module somewhere. Then in the place where I would have used krumo($target); I use watchdog('bug_hunt', explain($target, 5, 'target') ); and go to /admin/reports/dblog and filter for bug_hunt.  That 5 is arbitrary in this case; 4 steps into something can get you target->field_one[und][0][value] = Content.Since I have that function terminating the recursion with html line breaks, it reads well in the log pages.

I started doing this when I was trying to expound on processes that did not have a page for krumo to inject into (maestro module workflows, etc).  Since then, it has been a reliable fall-back method for me.

The better solution would be to spend the time finding why devel crashes your site, as it might be an issue that will appear again later on.


Find out what theme you're using (visit /admin/build/themes)
Find the files in your Drupal installation for that theme (if it's a core theme it'll be under /themes, if contrib it'll likely be in /sites/all/themes)
Change what you need to.

If it's a core theme, don't edit it (you'll lose the changes when you next update Drupal core) - create a subtheme instead.

The files in /sites/default/files/css are the optimised files produced when CSS aggregation is turned on; for development you'll want to disable that (/admin/settings/performance), or you'll need to clear the css cache every time you make a change.


Why does PhpSpreadsheet fail to identify my Xlsx file in public://?

Looks like PhpSpreadsheet can't read URIs, but only file paths.
You need to find the path to the file on the system.

$real_path_to_file = \Drupal::service('file_system')->realpath($file->getFileUri());

(Ideally you'd inject file_system and not call this service statically.)


You can use the nextUntil() jQuery function like this:

(function ($) {
  Drupal.behaviors.collapsibleTable = {
    $('tr.collapsitablesection').toggle(
      function() {
        $(this).nextUntil('tr.collapsitablesection').hide();
      },
      function() {
        $(this).nextUntil('tr.collapsitablesection').show();
      }
    ).click();
  };
})(jQuery);

Put this in the script.js of your theme if it has one, if not add a new one, see the documentation: Using the theme's .info file (Drupal 6 & 7).


Entity queue JSONAPI pagination & How to add JSON API in views?

Is sounds like you're assuming functionality that may-or-may-not be there.
Assuming /jsonapi/my-5-articles is an alias for /jsonapi/entity_subqueue/$MY_QUEUE_MACHINE_NAME?include=items, items[paging] isn't a query param for pagination, only page is (with [] options for specifying page size & offsets).
It sounds like what you want, in terms of the JSON API spec, is a paginated compound document (i.e. the included property that has all your queue nodes for the items relationship). Per the JSON API spec:

A server MAY choose to limit the number of resources returned in a response to a subset (“page”) of the whole set available.
A server MAY provide links to traverse a paginated data set (“pagination links”).
Pagination links MUST appear in the links object that corresponds to a collection. To paginate the primary data, supply pagination links in the top-level links object. To paginate an included collection returned in a compound document, supply pagination links in the corresponding links object.

It's optional for the JSON API module to supply pagination links. If it does supply them, it will be in the links document property for the resource you're requesting.
Since you're wanting pagination for included resources, the spec says:

To paginate an included collection returned in a compound document, supply pagination links in the corresponding links object.

I'm assuming "corresponding links object" is different from "top-level links" and they're referring to links property for objects within the included array.
From a quick look over the JSON API docs/code it doesn't appear to support this functionality. That may or may not be the case, you'll need to see if it does. You should check the project's issue queue.
The specs' flexibility on this scenario means the authors may not have put the functionality in there. If that's the case, you'll need to figure out a workaround or implement your own solution here.


How do I remove the inserted a span tag in an href parameter when using Full Calendar and Devel Themer

There are a lot of little bugs with devel themer. I would just throw a little jquery in one of the js files in the devel_themer module directory to hide any spans in that  tag

    $(document).ready(function() {
$('#divnamecontainer a span').remove();
});


you must add {"vid":"1234"} in the body of HTTP POST request and add Content-Type in the header request with "application/json"


Performance Implications when Views JOIN added twice?

Astonish Design did a good write up on this topic: Writing Efficient Queries in Drupal.

You should measure your specific queries though, it always depends on the amount of data you are working with, proper indices, mysql configuration and so on. Joining too many tables will almost always increase your query execution time, keep that in mind.


Caption on CKEditor with Media embed only allows 128 characters

This should do the trick no need to install any module, substituting 500 with whatever you want the limit to be

 function mymodule_form_entity_embed_dialog_alter(&$form, $form_state, $form_id) {
      if(isset($form['attributes']['data-caption'])) {
        $form['attributes']['data-caption']['#maxlength'] = '500';
      }
    }


Ubercart - how to alter button texts via hook_form_alter()?

There is a thread about this problem on drupal.org, and there is even a patch to solve this problem:
http://drupal.org/node/1170364

A quick explanation why the button text altering breaks up normal behavior (which is a bit "funny"):
Let's take a look at uc_cart_view_form_submit()'s code, mainly the part below the comment "// Specify the appropriate redirect based on the button used to submit". You can see that there's a switch block where the text of the clicked button is inspected ($form_state['clicked_button']['#value']), which is a very bad practice: the logic depends on what text this button is set to display. This means if you simply change the text of the buttons programatically, the appropriate redirections won't work anymore! To be honest, I don't really understand why this part of Ubercart was developed this way.

I just solved it with a custom module without patching the Ubercart core, and it works after some tests, you can find the code below.

About changing the "Continue shopping" text:

the "Continue shopping"  text can be easily changed on the /admin/store/settings/cart/edit/basic page, and as it's a multilingual variable, THIS is the appropriate way of changing it - you can do this by typing another name in the "Custom continue shopping link text:" textfield, and saving the changes. You can see a screenshot of it here:
BUT I also show you how to change it programatically (you can see it below in the code - you have to set the $set_continue_shopping_type_programatically to TRUE to try it - but I would suggest using the first method)
I also have to mention that the "Continue shopping" is a link (not a button) in Ubercart 6.x-2.7 by default - so if you would like to change its value programatically, and it is set to be displayed as a "Text link", its value has to be a link markup (not a regular string, because this way it won't work as expected) - you can use Drupal's l() function to create an appropriate link. But you can also set it to be displayed as a button, this way you have to use a plain text to modify its original text (and it turned out from your comment that you've already set it to be displayed as a button).

Here is the tested and working code:

// ...

// you should change MYMODULE to your module's name

/**
 * Implementation of hook_form_alter()
 * @see http://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook_form_alter/6
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id)
{

    // for testing, you can output the appropriate $form_id variable
    // to detect the form id(s) of the actual form(s) printed to the page
    // e.g. by using Devel module: http://drupal.org/project/devel
    /*
    if(function_exists('dsm'){
        dsm('Actual $form_id:');
        dsm($form_id);
    }
    */

    // You can just simply toggle overriding the default cart button values
    // with setting the variable below to "TRUE" or "FALSE" (without the quotes)
    // (this can be good for testing!)
    $modify_default_ubercart_buttons = TRUE;

    switch ($form_id) {
        // CHANGE IT TO THE APPROPRIATE $form_id!!!
        case 'uc_product_add_to_cart_form_1':
            // dsm($form);
            if($modify_default_ubercart_buttons){
                $form['submit']['#value'] = 'Register';
            }
            break;

        case 'uc_cart_view_form':
            // dsm($form);

            if ($modify_default_ubercart_buttons) {
                $form['#submit'][] = 'testModule_form_alter_uc_cart_view_form_submit';

                // 1.) changing the "Update cart" button's text

                $form['update']['#value'] = 'Update';
                // if you modify the "#name" attribute, you also have to modify it in testModule_form_alter_uc_cart_view_form_submit()
                $form['update']['#name']  = 'update-cart';

                // 2.) changing the "Checkout" button's text

                $form['checkout']['#value'] = 'Continue';
                // if you modify the "#name" attribute, you also have to modify it in testModule_form_alter_uc_cart_view_form_submit()
                $form['checkout']['#name']  = 'cart-checkout';

                // IMPORTANT!!!
                // You should rather set the "Continue shopping element display" on the "/admin/store/settings/cart/edit/basic" page!
                // This is a multilingual variable, so setting it on the appropriate admin page is the best solution.
                // The code below is just a sample for setting it programatically!
                $set_continue_shopping_type_programatically = FALSE;

                if ($set_continue_shopping_type_programatically) {
                    $uc_continue_shopping_type = variable_get(uc_continue_shopping_type, 'link');

                    $continue_shopping_link_text = 'Back';
                    // $continue_shopping_link_path   = uc_cart_continue_shopping_url();
                    if ($uc_continue_shopping_type == 'link') {
                        $continue_shopping_link_markup       = l($continue_shopping_link_text, $continue_shopping_link_path);
                        $form['continue_shopping']['#value'] = $continue_shopping_link_markup;
                    } else {
                        $form['continue_shopping']['#value'] = $continue_shopping_link_text;
                        // the default "#name" attribute equals to "op" by default
                        // we change it to the desired button text to make it clear
                        $form['continue_shopping']['#name']  = $continue_shopping_link_text;
                    }
                }
            }

            // ...

            break;
    }
}
/**
 * Ubercart submit function needed because of button text altering
 * @see http://drupal.org/node/1170364
 */
function MYMODULE_form_alter_uc_cart_view_form_submit($form, &$form_state)
{

    // Specify the appropriate redirect based on the button used to submit.
    switch ($form_state['clicked_button']['#name']) {
        // Update cart button.
        case 'update-cart':
            // No redirect.  Just display a message and preserve the last URL.
            drupal_set_message(t('Your cart has been updated.'));
            break;

        // Checkout button.
        case 'cart-checkout':
            $form_state['redirect'] = variable_get('uc_checkout_enabled', TRUE) ? 'cart/checkout' : 'cart';
            break;
    }
}

// ...

I also posted some screenshots about the button text altering:

Modifying "Add to cart" button's text:

BEFORE:

AFTER:

Modifying "Shopping cart" page's buttons:

BEFORE:

AFTER ("Continue shopping" as a "Text link"):

AFTER ("Continue shopping" as a "Button"):


How to make Drupal 8 use only relative URLs?

Maybe you can take a look at this function new to Drupal 8 :

file_url_transform_relative()

Once you pass an uri through file_create_url() you get an absolute url. You can then pass it to file_url_transform_relative() and you'll get the relative path if indeed it's pointed to a local file.


How to add a pager at both the top and bottom of a View

Ok, I solved it.

In my theme, I had copied all the content of classy theme because is like a copy of this.

In the theme exist an "templeate" folder, this have another folder called "views" inside this folder exist the file called "views-view.html.twig" in this file exist a few printing variables whit if conditions. All I had to do was copy the:

{% if pager %}
 {{ pager }}
{% endif %}

Condition almost at the end of the "template" and paste it where is above the content and voilà, I have my pager at the top and the bottom of my template.

I hope this be useful for anybody.

Thanks for your comments.


In your view settings, sound like you just need to (under Advanced) add a CONTEXTUAL filter of Nid and use Content ID from URL.


Create referenced node on the fly in Drupal 7?

You should use the Inline Entity Form module.

Provides a widget for inline management (creation, modification, removal) of referenced entities.
The primary use case is the parent -> children one (product display -> products, order -> line items, etc.), where the child entities are never managed outside the parent form.
Existing entities can also be referenced.


How to apply drupal_add_css by block_id in Drupal?

You can try this code. Paste this code in file template.php

function YOURTHEME_preprocess_block(&$vars) {
  // use dpm($vars) to see struct of variable $vars
  $delta = $vars['block']->delta;
  switch ($delta) {
    case 'abc':
      //add css here
      break;
  }
}

Block ID are

string 'block'
$variables['block']->module
$variables['block']->delta

You can check block delta to use drupal_add_css()


Menu blocks doesn't alter the DB at all during the installation. It uses the 'block' and 'block_role' tables from drupal core and creates several entries in the 'variable' table to store some config.

So here's what I would do:

Check admin/reports/dblog
Install the website locally with wamp or Acquia DEV Desktop (using
the import tab and backup migrate module) if you're on windows to do
some debugging.
Check the 'menu_block_admin_settings_form' function in
menu_block.admin.inc which is called when going to
admin/config/user-interface/menu-block


Ask Drush to list which modules have database updates available

drush updatedb --no (shorthand: drush up -n) will list them and take no further action.


To the best of my knowledge, no, there isn't a module out there to do this. I have seen something similar done in the past though, where a node would have an id of some sort provided, and a module would connect to an external service to load in information for the node.

I suspect you might want to think about writing a custom module to do this. If you haven't taken a look at https://drupal.org/developing/modules yet you might want to. Just remember when modifying functionality of Drupal you should never hack the core, but create/use a module instead.

I think what your gonna want to do is architect a way to know what you need to pull and from where, then use hook_node_view to change/add the data you pull from your DB/external service (https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_view/7)


Create an autopath or a token using entity reference of entity reference

Ok, that was easy. One has to enable the Entity Token module, which creates automatically nested tokens for all depths of entity references.


You may be able to use hook_views_query_alter to load only nodes which have node.updated value equal to NULL or ''.


How to automatically select the organic group audience when adding content?

OG group extras

  Extra functions, blocks, and views for Organic Groups 7.2. In
  particular, this module adds views and blocks needed by sites that are
  not using Panels.

This only works on OG 7.2 but not on OG 7.1. If you are using OG 7.1, you can use panels and add a create group content panel to the node page.


CCK ahah image upload working if admin, but not for others!

What Drupal version do you use?
May I have list of modules you have?
What messages do you have in watchdog?

First think I have is drupal permission problem.


This is just a CSS thing!  There a tutorial here on how to achieve it, but you're pretty much just looking at some CSS like the following.

Edit: The tutorial has now gone, but the CSS contained is very similar to that shown below, and a quick search in your favourite search engine will return similar results.

#BLOCKID {
    position: fixed;
    top: 0;
    left: 0;
    height: 160px;
}

Just apply the CSS to your chosen block and you're off.


Module weight not being respected in order of execution

The module weight can be updated in multiple ways

1) Using the Module Weight module which gives you an option to change the order of modules. This module allows only reordering of non core modules
2) Directly updating the weight field in the table "system". Refer to this link for more details.

Lesser the weight the module floats on the list and gets executed early


Form is not submit handler is not called

Change this:

$form['submit'][] = array('package_get_form'=> array());

to this:

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

btw.

function package_get_form($form, &$form_state)
{
    drupal_set_message('working');
?>
    <script language="javascript">
        alert("aaa");
    </script>
<?php
return;
}
?>

This looks really messy. Try that instead:

function package_get_form($form, &$form_state) {
  debug('test');
}

But the best option would be to use standard submit handler instead declaring your own name convention:

function pricepackages_form_submit($form, &$form_state) {
...
}


How to troubleshoot an Ajax HTTP Result Code 200 Error?`

The <?php tag at the beginning of the ResponseText indicates that there is a stray <?php in the markup, this was being caused by a syntax error in a completely unrelated template.
After template syntax error was fixed the Ajax Http 200 error pop-up went away.


Edit your view displays, make sure the common exposed filters have the same Filter identifier.  You can find this when you click the filter, and in the "More" fieldset.


How to unpublish nodes which are missing in migration source?

I have used an EventSubscriber for this. Here is my code.
/**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events = [];
    $events[MigrateEvents::PRE_IMPORT][] = ['archiveMissingNodes'];

    return $events;
  }

  /**
   * Archives the missing contact persons.
   *
   * @param \Drupal\migrate\Event\MigrateImportEvent $event
   *   The migration import event.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function archiveMissingNodes(MigrateImportEvent $event) {
    $migration = $event->getMigration();

    if ($migration->id() === 'my_migration_id') {
      $id_map = $migration->getIdMap();
      $id_map->prepareUpdate();

      // Clone so that any generators aren't initialized prematurely.
      $source = clone $migration->getSourcePlugin();
      $source->rewind();
      $source_id_values = [];

      while ($source->valid()) {
        $source_id_values[] = $source->current()->getSourceIdValues();
        $source->next();
      }
      $id_map->rewind();

      while ($id_map->valid()) {
        $map_source_id = $id_map->currentSource();

        $destination_ids = $id_map->currentDestination();

        if (!empty($destination_ids['nid'])) {
          $node = $this->nodeStorage->load($destination_ids['nid']);

          if ($node instanceof NodeInterface) {
            if (!in_array($map_source_id, $source_id_values, TRUE) && $node->get('moderation_state')->getString() !== 'archived') {
              $node->setNewRevision(TRUE);
              $node->set('moderation_state', 'archived');
              $node->set('revision_log', '');
              $node->setRevisionCreationTime($this->time->getRequestTime());
              $node->setRevisionUserId($this->currentUser->id());
              $node->setRevisionTranslationAffected(TRUE);
              $node->save();
            }
          }
        }

        $id_map->next();
      }
    }
  }


Modifying integer field to decimal gives error when editing field information

If the only tables that you have updated are field_config, field_data_field_nursing_note_max_temp and field_revision_field_nursing_note_max_temp then you missed one: field_config_instance.

Without being able to explain in detail how your manual mingling with the database produces the error, I'll try to outline what I understand.

The error you're seeing is produced in field_sql_storage_field_update_forbid. This is a hook implementation that is called by the Field CRUD API in order to give modules the chance to object the updating of a field:

// See if any module forbids the update by throwing an exception.
foreach (module_implements('field_update_forbid') as $module) {
  $function = $module . '_field_update_forbid';
  $function($field, $prior_field, $has_data);
}

The hook function receives three argumentes, the first is the current field definition coming from the field settings form, the second is the prior field defintion which is read from the field_config_instance table:

$prior_field = field_read_field($field['field_name']);

I assume that those two arrays differ and produce the error that you are encountering.

So I'd say, welcome to field hell! It's in general not advisable to mingle directly with the fields underlying table structure and column definitions. If you need to change a field, it might be a lot better to create a temporary field and migrate the data using API functions in batch scripts for example. That sounds like more work in the first place, but it will spare you these kinds of inconsistencies.


Need to redirect the non-existence URL's to 404 page instead of parent url

Considering the comments of the previous answer:

Only act on 'node' pages (aliased and not).
Avoid 'page not found' repeating 2 times.

Furthermore removed the unused variable $path.

The code below also avoids a 404 for the path 'node/add'. In case you use the Entity connect module that path might be followed by a dynamic token. The URL could then look like 'node/add/page/entityconnect-form-hmcOTIsupNLNBI-cZ-sSvjsbFISJeOfzT0VBpg0Sbpc'. Obviously that is a path not "known" by Drupal that would otherwise incorrectly result in a 404.

/**
 * Implements hook_init().
 */
function YOURMODULE_init() {
  // Only act on 'node' pages (aliased and not) but not on 'node/add'.
  if (arg(0) === 'node' && arg(1) !== 'add') {
    // Extract different variables that Drupal utilizes for routing.
    $menu_item = menu_get_item();
    $href = $menu_item['href'];     // node/1
    $current_path = current_path(); // node/1/broken

    // Check if the actual path ($current_path) is different than the Drupal assumption ($href).
    if ($href != $current_path) {
      // Redirect user to 404 page which will handle the HTTP response as well.
      drupal_not_found();
      // Avoid 'page not found' repeating 2 times.
      drupal_exit();
    }
  }
}

UPDATE:
There is now a Drupal 7 module Force 404 that solves just this.


Adding pager to queried content in a custom module Drupal 8

The format of the render array is wrong, you have to place the pager in its own render element (see this question, which was almost at the same time Pager with EntityQuery) or if you want to have it in the theme in a variable, but then a name other than #type.


Submit handlers only work in a form. If you want to put some kind of an action in render(), then use a normal link to an export display of the view or to a batch which uses an embedded view.


how to add a cck field for youtube embed code?

Use Drupal's Embedded Media Field. Here is a quote about it (from the module's project page):

This extensible module will create fields for content types that can be used to display video, image, and audio files from various third party providers. When entering the content, the user will simply paste the URL or embed code from the third party, and the module will automatically determine which content provider is being used. When displaying the content, the proper embedding format will be used.
The module is only an engine, and requires a supported module to function. These include 'Embedded Image Field', 'Embedded Video Field' and 'Embedded Audio Field'. These modules are included in the contrib folder of the module, so they can be easily activated from the module administration page.


What is the custom date format to display Days or Months ago in date field?

I think it's best for you to use the Timeago module: https://www.drupal.org/project/timeago

First, it provides a timeago date formatter option for use with dates anywhere, which answers your need.

Second, it solves the caching and correctness of time-ago dates problem for you automatically. Even though you don't mention this in your question, this is important as it's best to cache pages in live production in one way or another.

Good luck.


How and where should I override the character length of the description field for an exposed filter

After discussing it with Kevin in the comments above, I settled on a custom module to solve our problem. It's very simple and small module that includes the following:

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

if ($form_id == 'views_ui_config_item_form') {
    $form['options']['expose']['description']['#maxlength'] = 1000;
    }
}


Is the "www" in the database for the site confguration?

No its not there in database.

It depends on global $base_url variable.

How drupal define this variable is based on super global $_SERVER['HOST'] variable, which is basically depends on how the request was sent with/without www.

But you can override global $base_url in your settings.php
$base_url = 'http://yoursite.com'


I used this CSS technique to make checkboxes larger and add background images unique to each checkbox. Sample LESS Code:

#edit-field-vegetables {

  input[type='checkbox'] {
    -webkit-appearance:none;
    width:70px;
    height:70px;
    background: url('../img/vegetables_icons_long.png') no-repeat;
  }
  input[type='checkbox']:checked {
    opacity: 0.5;
  }

  .form-type-checkbox{
    display: block;
    width:110px; height:110px;
    position: relative;
    float:left;
    input.form-checkbox{
      float:right;
      position: absolute;
      top:40px;
    }
  }

  .form-item-field-vegetables-und-orange input {
    background-position: 0 -753px;
  }
  .form-item-field-vegetables-und-banana input{
    background-position: 0 -1415px;
  }
  .form-item-field-vegetables-und-apple input{
    background-position: 0 -80px;
  }
}

This works on chrome. Look at the discussion linked above to see how to make it cross-browser.


How do I programmatically export all webform submissions into a single csv? (multiple webforms)

As per your comment that you are interested in "an alternative to creating such CSV file programmatically": have a look at the Forena module (without using Views. Forena can do exactly what you're asking for (so no need for "programmatically").

As an example, create a custom "data block" (which is just an SQL statement) that fits your needs, to retrieve the webform data that you're interested in. Here is a (basic) example that I sometimes use for some testing:

SELECT s.nid AS node, s.sid AS submission, d.cid AS component, d.data AS fieldvalue
FROM {webform_submissions} s JOIN {webform_submitted_data} d ON s.sid=d.sid
WHERE d.cid=3 AND s.nid=5
ORDER BY s.sid ASC

Then create a Forena "report" that uses this data block, and make sure that within "document types" you enable the "CSV" option. Here is the (basic) layout of such report to illustrate the idea:

          node
          submission
          component
          fieldvalue

          {node}
          {submission}
          {component}
          {fieldvalue}

After you saved the report and browse it, you'll have a "CSV"-hyperlink (upper right of the report). Just use that link and ... voilà, there is your CSV file (in this case with 4 columns, since that is what in my (basic) report I asked for.

If this makes sense, head of to the Community documentation of Forena to get you going (which includes pointers to video tutorials). Or use the documentation that comes with Forena.

Of course, building the appropriate SQL statement to perfectly fit your needs is going to be crucial. But apart from that, it's just basic usage of Forena.

Disclosure: I'm a co-maintainer of Forena.


Change notification to different languages

I believe, the module, you need is Subscriptions

The docs say:

  "This module enables users to subscribe to be notified of changes to
  nodes"

It is actively maintained and was started in 2003.


Creating module with autocomplete and accepting multiple values in textfield

You can use the following code.

function _autosearch($string) {
  $matches = array();

  if ($string) {
    $items = array_map('trim', explode(',', $string));
    $last_item = array_pop($items);
    $prefix = implode(', ', $items);

    $result = db_select('users')->fields('users', array('name'))->condition('name', '%' . db_like($last_item) . '%', 'LIKE')->range(0, 10)->execute();
    foreach ($result as $user) {
      $value = !empty($prefix) ? $prefix . ', ' . $user->name : $user->name;
      $matches[$value] = check_plain($value);
    }
  }

  drupal_json_output($matches);
}

This is the result.

If you want to avoid a username can be used more than once, then you can use the following code.

function _autosearch($string = '') {
  $matches = array();

  if ($string) {
    $items = array_map('trim', explode(',', $string));
    $last_item = array_pop($items);
    $prefix = implode(', ', $items);

    $result = db_select('users')->fields('users', array('name'))->condition('name', '%' . db_like($last_item) . '%', 'LIKE')->range(0, 10)->execute();
    foreach ($result as $user) {
      if (!in_array($user->name, $items)) {
        $value = !empty($prefix) ? $prefix . ', ' . $user->name : $user->name;
        $matches[$value] = check_plain($value);
      }
    }
  }

  drupal_json_output($matches);
}


Domain Strict - Forces users to be members of domains in order to view content.

So they are still logged in to the whole system, that's what other modules can see.

The best you can do is to create your own module, or use PHP module to create a block with PHP filter. Use code similar to the one from this Drupal.org post:

// Count users with activity in the past defined period.
$interval = time() - 900;

// Perform database queries to gather online user lists.  We use s.timestamp
// rather than u.access because it is much faster is much faster..
$anonymous_count = sess_count($interval);
$authenticated_users = db_query('SELECT u.uid, u.name FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.timestamp >= %d AND s.uid > 0 ORDER BY s.timestamp DESC', $interval);
$authenticated_count = db_num_rows($authenticated_users);

// Format the output with proper grammar.
if ($anonymous_count == 1 && $authenticated_count == 1) {
  $output = t('There is currently %members and %visitors online.', array('%members' => format_plural($authenticated_count, '1 user', '@count users'), '%visitors' => format_plural($anonymous_count, '1 guest', '@count guests')));
}
else {
  $output = t('There are currently %members and %visitors online.', array('%members' => format_plural($authenticated_count, '1 user', '@count users'), '%visitors' => format_plural($anonymous_count, '1 guest', '@count guests')));
}

echo $output;

Now you have 2 modifications to make:

Get rid of the whole "anonymous" part, as you don't need it.
Modify the $authenticated_users = db_query part to JOIN the table Domain Strict module uses, and only count users that have access to the current domain.


Finally tracked down the isse to broken/partially updated menu  in some templates... they were causing the issue. have not been able to close the issue though.

hard reset of memcached fixed the issue... not nice to do in production site on busy day.
we had to look through the whole bootstrap to finally see this.


Try this:

$request_array = explode('/', request_uri());
if (in_array('work', array_values($request_array))) {
  //execute your custom code
}


Taxonomy - populate child dropdown based on parent dropdown?

In Drupal 6, a good way to do this is to use a single taxonomy vocabulary and make the children terms selectable via Hierarchical Select.  This will give you a single menu of the parents and then when users select one of the parent terms the menu of related children will automatically appear.

However, Hierarchical Select hasn't yet been fully ported to Drupal 7 (most notably, Views support does not work at all) and the timetable to do so is unknown.

For Drupal 7, you could try using the Conditional Fields module (or just use the States API directly if you're a developer) to set up logic to show/hide child menus based on the value of the parent menu.  However, doing so has two big drawbacks:

Users will see all fields if they have Javascript disabled.
Depending on the number of items you have, this can get very complicated.


How to set alias url for image address in a content type?

You could set your fields to use the private file system. For more information see Working with files in Drupal 7.

With the private file system, the path to files is of the form

www.example.com/system/files/path/to/file.png

The path /system/files is a drupal url, not an actual directory on your file system.

For your drupal file setting you set the path of the private file system to something like /sites/default/files/private so your images are on the server at sites/default/files/private/content_type_image

So the path to the image will be

www.example.com/system/files/content_type_image/path/to/file.png

then when a user hits that url the drupal callback for the system/files will check access control and then load the image from

/sites/default/files/private/content_type_image/path/to/file.png

Using the private file system also means if someone doesn't have access to the content the image is attached to then they cannot browse directly to that file if they can work out the path (and google can't index it) and it means that if you are using revisioning, users cannot see files attached to old revisions of your content, whcih they can with the public file system.

This is probably the best solution you'll get for stopping users from knowing the location of your files and also from accessing files they shouldn't be allowed to.


I use the SimpleCrop module, hope it fits your needs.

SimpleCrop provides the simplest workflow for manual crop of images. Basically, you can crop image in three steps: upload image => select area => save content. Functionality of this module covers more than 90% needs of manual image crops.
One of the key feature of this module is that this crop can be used as-is for the end users. So you don't need to theme or to add a workarounds to show this image crop to someone else. It has minimalistic and usable UI.


After Installing i18nviews Module, You should check admin/config/regional/translate/translate where you should search for the string

Here is a discussion going about it : Views pager translation not working


Temporary add role by token for a particular page to anonymous user

Assuming that this question is about D7, you could use the Rules module for this, combined with enforcing the usage of an URL argument which must include the correct token.

Here is an example of a relative path you could use/enforce: /node/123?SomeUrlArg=456, which would be for the node with node id = 123 and which uses an URL argument named SomeUrlArg and with the value of that URL argument 456 (obviously, each node can have its own argument value).

To implement this, you would create a custom rule that looks like so:

Rules Event: Drupal is initializing (you must use this event, otherwise you're too late).
Rules Condition: NOT (Check if the URL argument (=SomeUrlArg) is present and that its value matches the value of your field_access_token).

Note the NOT in this Rules Condition: you only want to perform the Rules Action below if either the argument is absent OR if its value doesn't match with the field_access_token value.

To be able to specify these Rules Conditions, you can use the Rules URL argument module. For more details about this module, refer to my answer to "How to use Rules to redirect a user based on URL argument?".
Rules Action: perform a redirect to whatever relative path that fits your needs (but not to /node/123 of course).


Generate one-time-use custom links for emails and interact with them to accomplish tasks

You can copy function "user_pass_reset_url" and form "user_pass_reset" and customize it for your needs. With first you create custom link and with the second you can get "one-time-link" logic.


Webform multistep form previous button asks to fill the required fields

For exactly this purpose the form has the #limit_validation_errors attribute. It is an array of values that will be validated instead of the whole form.

So to go back this woul mean an empty array since you do not want to valdiate anything.

But a small issue is that with empty array you will not be able to detect the button that submitted the form so you have to always include it in the list. If you have custom button #name use that, if not then use op which is the default.

Also these are the #parents values, not #array_parents so if you have a tree form you have to take that into account. Also using this will not only limit the validation, it will actually strip the submitted values, so if you want to go back but save some information(textfield) from the form, you have to include it as well.

For example:

$form['actions']['back'] = [
  '#type' => 'submit',
  '#value' => $this->t('Back'),
  '#submit' => ['::goBackSubmit'],
  '#limit_validation_errors' => [['op']]
];

or:

$form['actions']['back'] = [
  '#type' => 'submit',
  '#name' => 'go_back_submit',
  '#value' => $this->t('Back'),
  '#submit' => ['::goBackSubmit'],
  '#limit_validation_errors' => [['go_back_submit']]
];

or:

$form['#tree'] = TRUE;
$form['actions']['back'] = [
  '#type' => 'submit',
  '#name' => 'go_back_submit',
  '#value' => $this->t('Back'),
  '#submit' => ['::goBackSubmit'],
  '#limit_validation_errors' => [['actions', 'go_back_submit']]
];


I've been able to resolve this without using Scald templating.

The Scald plugin for CKeditor automatically inserts the image Title as the caption just below the image.  This text is editable in WYSIWYG if you want to replace the image Title with your own caption.

Below is how it looks at my site. Notice the caption just below the image.  (This is without any additional CSS - it can look nicer if you add some some CSS.)

And this is the markup inserted by the Scald plugin.  The caption is in the
 with the class dnd-legend-wrapper:

Fred Espen Benth. Foto: Gunhild M. Haugnes.


how remove required field from billing information into checkout

You have to use hook_form_alter to changing form elements options. This field is required because very often payments modules need this data to prepare correct post variables.


Hiding language names in "Language switcher" block and displaying only country flags

OK, in the meantime I found the perfect solution which I earlier just simply overlooked: there's a really simple configuration option in Language icons module's settings in http://<yoursite>/admin/settings/language/icons (D7: http://<yoursite>/admin/config/regional/language/icons) .

You have to set "Icon placement" option from "Before link" or "After link" to "Replace link", which results in displaying only the country flags.

Here are some screenshots (on the admin site I'm currently using RootCandy Dark):

BEFORE:

AFTER (on the admin site):

AFTER (on the main site's right sidebar [design is strongly under development :P]):


How do I use translated taxonomy terms in exposed views filters?

The answer to this is to use the i18nviews module, which is independent of the modules included in i18n. Once the module is installed then in your view chose Filter: Has taxonomy (translated terms).  Even though the selection will be in the source language they will then translate properly on the page views.

Note: at the time of this post il8nviews is in development, has little to no documentation, and is a bit difficult to work with, but hopefully that should be cleared up soon.


Turns out the form was not actually being submitted but the custom handler was not being processed because the form validation was failing. I disabled it with

$form['submitted']['name']['get']['#limit_validation_errors']=array();

and now the handler works.


How to hi-lighten with red border when multi check box fails validation.

Have you tried this module: Checkbox Validate ?

  Corrects bugs in Drupal core:

  Checkboxes set as required not displaying required symbol (install this module to display)
  Checkboxes set as required behave as optional (install this module to make behave
  as required field)

  This is the related D6 issue: #259292: Required radios/checkboxes are not validated (D6).


It's "core-recommended" as in "recommended to avoid having dependency-related trouble with core."
Drupal core (and some of the contributed modules, but not all) has a variety of automated tests that are run to make sure that everything is working as expected.  However, Drupal also needs dependencies to run. If you use different versions of the dependencies that were not tested, there might be a bug and the tests might not pass. core-recommended contains the specific dependencies that were used to test a given version of Drupal core.
By using core-recommended, you are guaranteed to get the same dependencies that were used to release that version of Drupal core, and Drupal core is only released when those tests pass.  So, you can be more confident when you are deploying your site because you know that your combination of core + dependencies is verified to work according to the tests.

let's say you install a dev version of a modul or any other third
party library with composer, which explicitly needs a different
version of a symfony component than drupal/core-recommended,

It's relatively rare for a contributed module to need a specific version of a Symfony component.  When you do need to use such a module and you switch from core/recommended to core, you might experience some Symfony-related or other dependency-related bugs because some of the dependencies may require changes in core that have not been made yet.  So when you do this, you are now responsible for running the tests, and if you encounter bugs you may have to search the core issue queue and apply patches, etc.
As for dev modules, it's never recommended to install dev modules on production, so whenever you install a dev module, you are taking responsibility for testing into your own hands.
TLDR: Recommended means "recommended because it passed the tests."  These are the recommended dependencies because they are known to work, but of course you can try to use others if you like. But, if you don't use the recommended dependencies and then you find a bug and think, "hey, core is broken, let's file an issue!", you should first check with core-recommended to make sure the issue isn't specific to the contrib module/dependency that required you to remove core-recommended.


Where does a blank theme inherit its templates from?

So from where it got html structure.

It comes from either your theme's base theme, or the default HTML template file included in the system module.


I found this module Menu Firstchild maybe it will do what you want it to do.


Unserialize error in Drupal Commons 3 for unathenticated pages

Since this was a development server, I just blew away the current install and database. This hasn't occurred since a reinstall of Commons 3.


How do I programmatically create a simple 'page' node?

The Devel project includes a module called Devel Generate for generating dummy content. You could use it as an example. I think the parts you'd need are in the devel_generate.inc file.


What would be the alternative to fix "Access forbidden 404" on my test site while using basic_authentication module for rest resource?

You can send in the user and password parameters with your API call.

user:password@http://site-url.tld

this way you can still communicate with the app whilst keeping it behind basic auth


How do i fix Invalid arguments passed in DefaultMailSystem->format() (line 23 system.mail.inc

I fixed it by using:

$language = user_preferred_language($user);