How can I randomize search results in Views?

Results are displaying in ascending order because you may have another sort criteria present above Global: Random (asc) like say Content: Post date (desc).

Solution: Move Global: Random (asc) sort criteria to top. Surely it will work.

  Note: If you have more than one sort criteria lets say 3, then results
  first get sorted with first criteria then with second and then with
  third.


This is a bit of code can help you I hope,

 <?php
   check_vocabulary = FALSE;
     $path = drupal_get_path_alias($_GET['q']);
     $pathnew = explode('/', $path);
     if ($pathnew[2]) {
        $vocabulary = explode('+', $pathnew[2]);
     }
    if ($vocabulary[0] == "your taxonomy") {
       check_vocabulary = TRUE;
    }
  return check_vocabulary;
?>

You should put it in the block under the tab Page specificy visibility setting, click on Show if the following PHP code returns TRUE (PHP-mode, experts only).

Now I'm not sure it's going to work with your setting and name but it could be a way for a solution.

 check_vocabulary = FALSE;

As we know, the system wants you to return TRUE to print the block so we set it false in the beginning so it's no going to print it and then remove it.

$path = drupal_get_path_alias($_GET['q']);
$pathnew = explode('/', $path);

In this part we take the path and we explode it so we get an array like this.

$pathnew[0]; Taxonomy
$pathnew[1]; Term
$pathnew[2]; Term_id_1+term_id_2

if ($pathnew[2]) {
    $vocabulary = explode('+', $pathnew[2]);
  }

We check first that $pathnew[2] exists and then we explode it to get all the vocabularies (if you want it separated). We split it by + so you will get

$vocabulary[0]; Term_id_1
$vocabulary[1]; term_id_2

Now we create the condition;

if ($vocabulary[0] == "your taxonomy") {
   check_vocabulary = TRUE;
}

You can compare what you want, that is just an example.

check_vocabulary = TRUE;

This is what the system wants to print the block.

return check_vocabulary;

This will return the variable FALSE or TRUE.

Let me know if it works.


Make a copy of the live site for localhost testing

You can easily do this with the backup and migrate module. If you have lots of dynamic content you should be using this module to schedule a backup on cron jobs too.

Before I learned how to use the MySQL command line, because phpmyadmin has an import file size limit, I would compress a whole website with the backups in a private file path and move it to a new server. Then I just remove the database settings and install a new installation of Drupal. After I will enable the backup and migrate module and restore that last database.


The code you are using doesn't work as expected because you are first setting $node->changed, and then calling node_save(), which then unconditionally sets its value.

The code it uses is the following one.

// Set the timestamp fields.
if (empty($node->created)) {
  $node->created = REQUEST_TIME;
}
// The changed timestamp is always updated for bookkeeping purposes,
// for example: revisions, searching, etc.
$node->changed = REQUEST_TIME;

$node->timestamp = REQUEST_TIME;
$update_node = TRUE;

// Let modules modify the node before it is saved to the database.
module_invoke_all('node_presave', $node);
module_invoke_all('entity_presave', $node, 'node');

If you want to set $node->changed, you would need to implement hook_node_presave(), which is invoked right after node_save() sets
$node->changed.
For example, in the code you are showing, I would add $node->release_change_date = strtotime($data->Release->LastChangeDate);; your implementation of hook_node_presave() would then use $node->release_change_date to set $node->changed ($node->changed = $node->release_change_date).


The only solution I could come up with, to translate the menu title is by using the following:

$menu = menu_load('main-menu');
$menu_title = i18n_string_translate('menu:menu:main-menu:title', $menu['title']);
$menu_desc = i18n_string_translate('menu:menu:main-menu:description', $menu['description']);


Adding a submit button in a themed table doesn't work

Use instead of #theme a form element #type:
'#type' => 'table'

The table form element has an extra step for processing when used in a form.
You don't need '#rows'. Any array key not starting with #, also the index added automatically by appending a row with [], is considered to be a renderable child and displayed as row.


Add "webforms like" values to profile.module select list

Try Content Profile module. Using this module you can create user profile where you can add cck fields to the user profile content type.

  This module builds user profiles as content (aka nodes), which opens
  the opportunity to use all the powerful modules for content for user
  profiles too, e.g. the Content Construction Kit (CCK). It's intended
  to be simple and useful, but extensible by further modules.


Looking for a workflow module that can control content access

Update and solution: Turns out that I was not using the Workflow module correctly and Drupal's permissions correctly. I was assuming that the Workflow module could remove permissions. Instead I had to start with the least privileges in Drupal and then let the Workflow module allow/deny access to the content type.

For example, if Drupal permissions allow a visitor to see unpublished content, then the Workflow module's content access control will not block the person from seeing unpublished content.


How to use field_attach_update for users

I don't know your function my_module_import_user return right data? I think user_save() work fine. You can try

if (isset($uid)) {
  $account = user_load($uid);
  $edit = array();
  $edit['field_FIELD_NAME'][LANGUAGE_NONE][0]['value'] = 'Field Value';
  // add more data
  user_save($account, $edit);
}

if you want use field_attach_update

if (isset($uid)) {
  $account = user_load($uid);
  $account->field_FIELD_NAME[LANGUAGE_NONE][0]['value'] = 'Field Value';
  // add more data
  field_attach_update('user', $account);
}

And my way, i often use Entity metadata wrappers

if (isset($uid)) {
  $account = user_load($uid);
  $wrapper = entity_metadata_wrapper('user', $account);
  //Set data of field
  $wrapper->field_FIELD_NAME->set('Field Value');
  // set more data here
  $wrapper->save();
}


The missing modules don't get installed after updating with Composer

Remove your Composer lock file and run following command in sequence:

composer clear-cache
composer install
composer require Drupal/module


Show users pictures who have flagged a node

I think you'll have to create a user view, displayed as a block, and use the flag relationship to the nodes. Then use a contextual filter, taking the node NID from the URL as default.


db_delete on click on a link in module contents display

Add path to delete your elements to hook_menu().

$items['something/%/delete'] = array(
  'title' => 'Delete',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('mymodule_delete_form', 1),
);

In mymodule_delete_form(), use confirm_form(). It will generate "are you sure?" form for you. Then, just write mymodule_delete_form_submit() to perform actual deletion.


Using the Rules module, is it possible to access the fields of a referenced entity of an entity?

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.


count entityreference multivalue field conicidences (make an attendance form)

Solved. This is what I did. In order to not make heavy loads i enebleded Entity Construction Kit (eck) module, then by rules i added an entity (instead of a node) for every user entity reference value, within two columns, one for user name, and one for date in attendance. Now I can have a view (of entities) with two exposed filter on dates (beginning and ending dates) Then I override my views table tpl view with the following code. It displays a 2 column table, first: username, second: number of days that user has attendance.  the following code assumes that username is second field on your view ($fieldloop == 2 ). code:

<?php $names = array(); ?>

<?php foreach ($rows as $row_count => $row): ?>
   <?php $fieldloop = 1; ?>
    <?php foreach ($row as $field => $content): ?>
    <?php if ($fieldloop == 2 ) {$names[] = strip_tags($content);} ?>
    <?php $fieldloop = $fieldloop + 1; ?>
    <?php endforeach; ?>
<?php endforeach; ?>

  <?php $attendances = (array_count_values($names)); ?>

Alumno	# dias

<?php foreach ($attendances as $attendance => $value) : {
?>
  <?php print $attendance ; ?>
 <?php print $value; ?>

<?php } endforeach; ?>


You should check out Facebook Autopost. There is a video tutorial on how to set up everything to do it easily.

With this module you will be able to post Links, Posts, Events, Questions, … linked to Drupal events.


Change Add To Cart To Buy Now drupal Commerce

If you want to alter the text for a particular form you can alter it using hook_form_alter

Get the ID of the form for the product display where you are trying to change the text & do something like this:

function MYMODULE_form_alter(&$form, &$form_state, $form_id){//replace your module name with MYMODULE
  if(strpos($form_id, 'commerce-cart-add-to-cart-form-65') !== false){//my form ID is "commerce-cart-add-to-cart-form-65", replace it with your form ID.
    $form['submit']['#value'] = t('Buy Now');//Put the text which you want to make appear instead of "Add to cart".
  }
}

You could also use String Overrides Module to achieve the same.


The possible ways are:

1) using a CSS file, ex: style.css (located in your /sites/all/themes/YOURTHEME/css folder)

.block { border: solid red; }

2) using jQuery, ex: style.js (located in your /sites/all/themes/YOURTHEME/js folder)

$('.block').css({"border":"solid red"});

3) using a template file, ex: block.tpl.php or view.tpl.php (located in your theme's /sites/all/themes/YOURTHEME/template folder)

<style>
.block { border: solid red; }
</style>

4) Inside the view, if they add a header or footer of text area or unfiltered text and then put inside the header/footer:

<style>
.block { border: solid red; }
</style>

or

<script src="myScript.js"></script>

5) Using the CSS Injector module

6) Using the JS Injector module


How to redirect in WebformHandler after submitting Ajax form

I got it working with another approach, instead I used the form_alter hook and added an ajax submit callback.
See Webform alter with ajax submit callback - field values are empty in callback


How can I send an email to site admin and vice-versa when user returns a product using commerce_rma?

You could use Rules Module

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events

There are events created in rules when Commerce RMA is installed such as After creating a new return


Option 1: Try to increase your php memory limit above the 250 MB.

Option 2: Don't try to debug all the rows at once.

{{ for row in rows }}
  {{ kint(row) }}
{{ endfor }}

P.S.

The reason {{ row }} was null, was because that variable does not exist in the template unless declared like in my example above.


How to skip (don't update) some fields from existing node during import if this field already has a value?

Had the same problem. I finally used hook_feeds_presave(), and unset the field I wanted to skip. Here's the code:

function mymodule_feeds_presave (FeedsSource $source, $entity, $item, $entity_id) {
  if ($source->importer->id == 'myimporter'){
    // I check if my imported value is equal to a special marker i set
    if ($entity->my_field['und'][0]['value'] == 'MARKER') {
      unset($entity->field_i_wanted_to_skip);
    }
  }
}

This automatically resets THAT FIELD ONLY. Hope this helps someone.


How do I install Commerce Kickstart as a Aegir installation profile

If you download the .tar.gz from http://ftp.drupal.org/files/projects/commerce_kickstart-7.x-2.0-rc4-core.tar.gz into your platforms directory on aegir, untar it, and then create a platform with the same name you can build sites using the commerce kickstart profile with aegir.  Here are the commands I used:

cd /var/aegir/platforms
curl -O http://ftp.drupal.org/files/projects/commerce_kickstart-7.x-2.0-rc4-core.tar.gz
tar xzf commerce_kickstart_7.x-2.0-rc4-core.tar.gz
mv commerce_kickstart_7.x-2.0-rc4 commerce-kickstart
chown -Rf aegir\: commerce-kickstart

Then go into Aegir and create a platform.  Set the platform directory to this commerce-kickstart directory and don't include a build file.  It'll verify the platform and then you'll be able to create sites on there using the Commerce Kickstart installation profile.

Cheers,
Diwant


Getting the uid from user name for a view argument

Use the Data name argument to filter the results by. Each content field has it's own argument that you can choose to filter the results by.

(edit: reply to comment) Let's say that your drupal username is user3 with a UID of 3. The user ID of the external data will be user3? So when the user goes to mysite.com/user/3 the argument will be 3 which doesn't help with the external data because that needs to be mapped to user3? If the user ID of the external data is 3 then you can use data: field_userID or whatever it is and get arg(1) using provide default value from PHP code, page manager or Views Arguments from Context. Now, if you to map the Drupal username to the external data username/user ID which is user3 then use provide default value from PHP code, get the global $user variable and use $user->name for the argument. This maps the user's name to the database column in the data table and returns (filters) all results/ database rows with that username in that column.

Don't validate it until you get it working.

global $user;
return $user->name;

or

return arg(1);


Remove duplicate records from views feed display for node with multiple grouped terms from one vocabulary

Here's what I came up with that does the job:

/**
 * Implements hook_views_query_pre_render().
 */
function video_export_views_pre_render(Drupal\views\ViewExecutable $view) {
  $unique_nids = $new_results = array();

  // Loop through results and filter out duplicate results.
  foreach($view->result as $index => $result) {
    if(!in_array($result->nid, $unique_nids)) {
      $unique_nids[] = $result->nid;
    }
    else {
      $new_results[] = $result;
    }
  }
  // Replace $view->result with new array. Apparently views requires sequentially keyed
  // array of results instead of skipping keys (e.g. 0, 2, 4, etc), so we can't just
  // unset the duplicates.
  $view->result = $new_results;
}


Menu links are only created by default because the default type for a router item is MENU_NORMAL_ITEM:

  Menu type -- A "normal" menu item that's shown in menu and breadcrumbs.

What you need is a MENU_CALLBACK:

  Menu type -- A hidden, internal callback, typically used for API calls.

e.g.

$items['example/feed'] = array(
  'title' => 'Example RSS feed',
  'page callback' => 'example_feed',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
);

That will create you an accessible path with no menu links, unless of course you add them manually through code or the UI.


Is there a way to stop Order checkout in Commerce 2.x?

Use Commerce's AvailabilityManager service.

See https://www.drupal.org/node/2511266 and https://www.drupal.org/node/2710107 for more information.


How can I filter a view to show recent items but only one item per user?

A dull ax approach would be to create a View that returns 100 of the latest messages, and then using a views_pre_render() hook, go through and grab the messages uniquely per user, eg, something like this:

function YOURMODULE_views_pre_render(&$view) {

  if ($view->name=='THIS_VIEW') {

    $new_result=array();
    $unique_users=array();

    foreach ($view->result as $row) {
      if (!in_array($row->USER_FIELD_IN_VIEW, $unique_users)) {
        $new_result[]=$row
        $unique_users[]=$row->USER_FIELD_IN_VIEW;
        if (count($new_result)==10) {
          break;
        }
      }
    }

    $view->result=$new_result;

  }

  // any other pre_render()ings go here

}

where USER_FIELD_IN_VIEW is the field in your View corresponding to the uid of the owner of the message.  A print_r() of $row or $view->result should give you that information.  The other kicker is picking a small enough number of messages to give you those 10 users. I just pulled out 100 out as 10 users and 10 messages per "hyperactive" user to make sure you got at least 10 users without getting too many that you just throw away at the end.

EDIT/ADDITION: there were some variable name typos in my code that I've corrected :)


Get the position of a paragraphs entity in a nested template

For the Slide, are overriding the default field.html.twig template?
If yes, then you can use the Twig Loop variables:
https://twig.symfony.com/doc/2.x/tags/for.html
e.g. loop.first


Is it necessary to have a separate voting tag for each rating when using Fivestar?

Yes, you need a separate voting tag for each ratings in the same content type, if you use the same for multiple fields, each field will recieve the same rating.

You can make a test, create two fields with the same tag, go to create one node and rate one field, refresh the page and you will see the same rate in the other field.


Set allowed value of a list field depending on the URL

You're making this a little more convoluted than it needs be; the core arg() function can parse out the path and get the 4th element; the query is also broke (condition() is passed a string literal instead of variable & it's missing aliasing argument); lastly you could help readability with a switch control.

  //fields() needs an alias argument $group_id can be pulled from arg()
  $og_type = db_select('node','n')
    ->fields('n', array('type'))
    ->condition('nid', arg(3), '=')
    ->execute()->fetchField();


If you simply want to find out what is inside $commerce_order then you can use

<?php echo var_dump($commerce_order);?>

I have made a module in the past that did a simerler thing to what you are trying to do.
Using Ubercart I created a module that took advantage of the hook_order function.

<?php
function myFunction_uc_order($ops, &$arg1, $arg2){
    global $user;
    $userId = $user->uid;
    if ($ops = 'update' && $arg1->order_status == "payment_received" && $arg2 =="completed"){
        $order = uc_order_load($orderId);
        //$order now contains all order information for the current order
    }
}
?>

This code will be run every time an order is "updated", this includes being created. So inside the if you can add your code to export to your 'external' database.

Hope this helps


As @anonymous pointed out, it is answered in Access user profile data.  Since that post is not well labeled in connection with rules, I will also post the answer here.  In short, instead of verifying Entity is of Type, verify that entity is of bundle.  Entity of Type should work, but that it does not is (apparently) a known bug with Rules 8.x-3.x as of this time.


Using MYTHEME_page_attachment_alter does not alter the favicon

If its not a browser cache issue perhaps you should try modifying it with a hook called later namely THEMENAME_preprocess_html

function THEMENAME_preprocess_html(array &$variables) {
  $test = "";
  $variables["page"]["#attached"]["html_head_link"][0][0] =
    array(
      'rel' => 'shortcut icon',
      'href' => '/themes/fu/favicon_urbana.png',
      'type' => 'image/png',
    );
}


The solution came down to replacing "views" with "view" - without the s and "views_page_machine_name" with "all", such that this:
entity_print:
 views:
   views_page_machine_name : 'theme_name/result-pdf'

became:
entity_print:
 view:
   all: 'theme_name/result-pdf'


Overwrite taxonomy/term page with custom view isn't working

Keep in mind

The taxonomy path is normally taxonomy/term/% ( not taxonomy/% )
Views ships with a default taxonomy/term/% override ( just needs enabling )

Perhaps that will help.


How to check order exist or not in commerce order?

You can check this using commerce_order_load()

if(commerce_order_load($order_id)){
    //Do something
}
else{
   //Do something
}

Hope this will help you


Injecting database values with a non-Drupal application

One method would be to use the Services module to create a web service that the external program could then communicate with.


In my experience, the structure you're looking for is created by the template layer. I would not recommend changing the link array directly. A good example template is core's stable theme's menu.html.twig. It uses a recursive twig macro to create nested lists.


Get title of referenced item two levels deep with Search API

None of the relations information is stored in C, so when you have C views it can't show relations info out-of-box.

Usually the way to show the "Child" for a "Parent" node is by using the Contextual filter for the Entity Reference field with the "provide default value" and "Content ID from URL" options. In your case A is a child of B, and B is a child of C.

Then you can use the Custom text field to construct your text, you can use the Contextual arguments in that field, this will give you information about the "Child" of the node in view row.

Maybe you can work through that to get to the "Grandchild" info, I haven't tried it.

I'd suggest chaining the reverse Relationships, they are called something like "Content referenced from field_my_reference", first you add the one for the child, then add another Relationship for the grandchild, and make the second Relationship use the First one. That's how you get to correct nodes.

Add the fields for the B and A titles with using the correct Relationship for each. Thena again you can use the Custom text field to override how their output is worded. You can "Exclude from display" the fields you use in Custom text after you have it showing the way you want inside Custom text.


The best way would be to make a custom page using hook_menu(), and have a submit function on that page that would check the user's authentication, and if it was correct, change the current password.

If you need a bit more information on that, I'm happy to help.


Is there a way to create CSS image styles?

What you are looking for is considered theming and is done mainly in the theme's template.php file.

There is a guide available here: Add bootstrap image css class to pictures

<?php
/**
 *
 */
function THEMENAME_preprocess_image_style(&$vars) {
        $vars['attributes']['class'][] = 'img-responsive'; // http://getbootstrap.com/css/#overview-responsive-images
}
?>


How to change Drupal module load sorting(weight) order

You can do this by using Modules Weight module.

  This module provide admin interface for users/people has the access to
  modules page to reorder the module weights as they want.


How to display the 'Request New Password' page for Administrators.

Think you'd need to do it with Views Bulk Operations and Views.

Create a View (only accessible by the Admin role) which lists all the users, add VBO and I think reset password is included as one of the actions.


if you using ckeditor firstPut your block text format on FULL HTML then   click on soruce  and finally paste your markups there.


Live site still taking nodes url as localhost/

Try clearing all Drupal caches at yourwebsite.domain/admin/config/development/performance


Simulating Facebook videos embedding behaviors in Drupal?

The emfield module does that. It's D6 only at the moment.


You're currently referencing the global $user object, then in the very next line you're overwriting it with a string (the username). So your global $user object is destroyed, and you will probably be logged out of the site (as well as the code not working as expected).

You're referencing the global user object in the correct way, but by default it isn't fully loaded (i.e. with fields attached, etc). To get the extra data you should use the user_load() function like so:

global $user;

// Get the fully loaded user object
$account = user_load($user->uid);

// Get the username. Make sure you don't override the global $user object here!
$username = $account->user.

// Get a field value.
$field_items = field_get_items('user', $account, 'field_foo');


Taxonomy manage fields wrong field edit url

The problem solved by simply patching the field module file-> field.module function named  field_extract_bundle

function field_extract_bundle($entity_type, $bundle) {
  if (is_string($bundle)) {
    return $bundle;
  }

$info = entity_get_info($entity_type);
if (is_object($bundle) && isset($info['bundle keys']['bundle']) &&     isset($bundle->{$info['bundle keys']['bundle']})) {
return $bundle->{$info['bundle keys']['bundle']};
}
//ADDED THAT ELSE
else{
  return $bundle->machine_name;
 }
}

the function tries to return the machine name of the entity as appeared above.

By doing some debugging I realized that the the object sent in the calling function field_ui_field_overview_form file->field_ui.admin.inc is n't the same as sent in drupal script before our continuous development in that project.

We added many other modules and edit configuration but the most related that I think caused that issue is features exporting the taxonomy vocabulary as the bundle object is the same exported in features so it may be some missing or conflict happened when deploying vocabularies with features

Please contribute your ideas!


Can we call a custom block inside our hook_block_view()?

Yes, you can load any block

....
$block['content']= sample_module_block_content();
....
function sample_module_block_content(){
  $block = block_load('module_name', 'block_name');
  return _block_get_renderable_array(_block_render_blocks(array($block)));
}


ImageCache throwing 500 internal server error

I've just ran into this issue and i solved it by enabling the ImageAPI GD2 module and disabling the ImageAPI ImageMagick module.

There's also a number of things to check: presence of the GD library in system and in PHP config, enough PHP memory to parse the images, valid file system configuration and permissions, etc.


How to change a field value to 500 products (commerce module) at the same time?

Well I can come out of two ways of doing this. One of them is Using the commerce API which is really good you just have to get all your 500 products with the following method:

 $query=new EntityFieldQuery;

    $query= $query->entityCondition('entity_type','commerce_product')->execute();

    foreach($query as $entity){
       $entity->commerce_stock[LANGUAGE_NONE][0]['value'] = 1;
       commerce_product_save($new_product);
    }

Or you can also do it on the database updating the value of the table field_data_commerce_stock:

update field_data_commerce_stock set commerce_stock_value=ANY_NUMBER;


How to check the modules installed date?

You can't have that information with default core and contrib module.

You can get the time module upload on your server by checking last modify time of module file.

If you realy want to have module install information, you should create a patch that change the module_enable function on includes/module.inc file.


Drupal 7 views join two profile2 profiles together

Have you tried Display Suit.

Also panels is a good solution for this.

Oskar


How to expose individual form elements from user-register-form

If your doing your own module hook_form_alter is the way to go. so long as all required fields are already supplied you should be able to set all other fields to have type hidden.

If you are looking to do something similar you may want to look at the event and rspv modules.


How to make an nid replacement in a Text area inside Footer?

For the current node ID try this token:

[current-page:url:unaliased:args:value:1]

See http://www.drupal.org/node/1360922


Ajax Submit Forgot Password Form Loaded in Front Page

module_load_include() works slightly differently from your example. The first argument is the file extension, the second is the module name, and the third is the file name minus the extension.

This should work:

module_load_include('inc', 'user', 'user.pages');


Solved! I found this post - https://drupal.stackexchange.com/a/52788/260 - which answered a very similar question, and that changed everything. This issue is essentially a duplicate of that one.

The fix here in my case was to not just change the link's href but to also update the Drupal.ajax object, like this:

Drupal.ajax['load-more'].options.url = link;

"load-more" is the ID of the AJAX link.


The simpletest module has been integrated into Drupal 7 core. Since then the contrib simpletest module has not seen much development. See also this issue.

If you want to start writing tests for your own modules, enable the core simpletest module (called Testing in the UI) and do not install the contrib module. Also check out the examples module, it should give you an idea on how to add tests for custom code.


Adding dividers between list items in the menu.html.twig template

See The Loop Variable in the Twig docs; you can use something like

{% if loop.last == false %}

{% endif %}


You can't skip versions when you upgrade. For instance you cant go from 6.0 to 6.2 in one step. You also can't upgrade directly from 6.0 or 6.1 to Drupal 7. You have to have your Drupal 6 installation at the latest level.


How to get a Drupal 7 Services 3 custom resource to fire

You need to wrap your retrieve resource in an actions array:

function my_feed_services_resources() {

  $my_resource = array(
    'myresource' => array(
      'actions' => array(
        'retrieve' => array(
          'file' => array('type' => 'inc', 'module' => 'my_feed', 'name' => 'my_feed.services'),
          'callback' => '_myresource_retrieve',
          'help' => 'Lorem ipsum.',
          'args' => array(
            array(
              'name' => 'myparm',
              'optional' => TRUE,
              'source' => array('param'),
              'type' => 'string',
              'description' => 'Lorem ipsum',
            ),
          ),
        ),
      ),
    ),
  );

  return $my_resource;
}

You can then "fire" it by doing a POST to: ?q=[my-endpoint]/myresource/retrieve.json

Don't forget to attach the X-CSRF-Token header to your POST calls. Its value can be retrieved here: ?q=services/session/token


This value can be set in the site information admin settings form.

$count = variable_get('default_nodes_main', 10);

This should work for both Drupal 5, 6 and 7.


As you want to create url object from a path instead of route, use the function fromUri() instead of fromRoute().

$url  = Url::fromUri('internal:/progetti');
$variables['items'][]['value'] = array(
  '#type' => 'link',
  '#title' => array('#value' => 'sergio'),
  '#url' => $url,
);

In fromUri() function you need to pass the URI of the resource including the scheme. For user input that may correspond to a Drupal route, use internal: for the scheme.


passing page arguments to drupal 8 from controller to form controller

Update the .routing.yml file like so:

test.check-test:
  path: 'node/{node}/test'
  defaults:
    _form: '\Drupal\test\Form\Test'
    _title: 'Test'
  requirements:
    _permission: 'access test'
    node: \d+
  options:
    _node_operation_route: TRUE

Then use it in your form controller the following way:

namespace Drupal\test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;

class Test extends FormBase {
  public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
    $form['placeholder'] = [
      '#markup' => t('This is the form for @node_title.', [
        '@node_title' => $node->getTitle(),
      ]),
    ];

    return $form;
  }
}


Off the cuff, this should work:

$view = views_get_view($view_name);
if ($view && $view->access('stats')) {
  // it has a 'stats' display
  $view->set_display('stats');
  $view->pre_execute();
  $view->execute();
  return $view->result; // or do whatever with it...
}

but realize at this point you're halfway through the 'heavy lifting' views does, so you should probably use $view inside that if instead of then calling views_get_view_result()

ADDITION:  I added what I think the correct $view incantations should be for getting just the results above :)


How can I programmatically render a node's field respecting the view mode settings?

To render a single field with the display setting of a view mode you can use the view() method of the field:

Example for rendering the image in teaser format:

$build['image'] = $node->field_image->view('teaser');

Or the body in full:

$build['body'] = $node->body->view('full');


Please set E-mail format Plain Text to Full HTML in Mime Mail Settings


The field will be named whatever you named it when you added it. If you can't remember, go to the "Manage fields" UI page for the relevant entity type/bundle and you'll be able to find it there.

The table names will be based on that field name; if the field is called field_my_field then the two database tables are:

field_data_field_my_field
field_revision_field_my_field


How to populate an autocomplete using a web service?

There is not, as far as I can tell, a module that addresses this currently, though it wouldn't be terribly hard to build with some time on google.

But since you don't intend to harvest the responses from the API a javascript/jQuery solution may be the easiest route. Any time I build a new site I set up a module to house custom functionality in that is specific to the site, I suggest you throw together a .module and .info file and add your js that way, Drupal documentation on putting together a custom module is pretty extensive.

If this helps:

$("input#autofill").autocomplete({
        source: function (request, response) {
            var term = request.term;
            var restUrl = 'http://myRestService.com/search/'+term;

            $.getJSON(restUrl, function (data) {
                var items = [];
                $.each(data.results, function (key, val) {
                    var item = {
                        label: val.Label,
                        value: val.Value
                    };
                    items.push(item);
                });

                response(items);
            });
        }
    });


You can't get the file from $form_state->getValue(). You have to upload the file first to the file table as temporary file with file_save_upload(). Then you can load the file content locally from $file->getFileUri().

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

    $validators = ['file_validate_extensions' => ['txt']];
    if ($file = file_save_upload('file', $validators, FALSE, 0)) {
      $data = file_get_contents($file->getFileUri());
      drupal_set_message($data);
    }

  }


Simplest way to have dynamic content (year) in field's default value?

you can write a module and implement hook_node_save(). If the node is new just set the value of the field (a simple text string to something like:

$node->field_copyright_notice[LANGUAGE_NONE][0]['value'] = "&copy; Copyright Our Organisation ".date('Y');

So in your own module you could do:

function MYMODULE_node_presave(&$node) {
 // Only do this for new nodes, eg nodes without a NID.
 if (!isset($node->nid)) {
     // Set our copyright text string.
     $node->field_copyright_notice[LANGUAGE_NONE][0]['value'] = "&copy; Copyright Our Organisation ".date("Y");
 }
}

// You can also hide the field for new nodes with hook_form_alter().
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_NODETYPE_add_form') {
    $form['field_copyright_notice']['#access'] = FALSE;
  }
}


How do I show the last created node in a block, without using Views?

The recommended way would be to create a custom module that will find/load the node and display in a block. Assuming Drupal 6 from your previous questions.

In your custom module:

<?php
/**
 * Implementation of hook_block()
 */
function YOURMODULE_block($op='list', $delta=0, $edit=array()) {
  switch ($op) {
    case 'list':
      $blocks[0]['info'] = t('Last Node Created');
      return $blocks;

    case 'view':
      // Get the last created node
      $nid = db_result(db_query('SELECT MAX(nid) AS nid FROM {node}'));
      $node = node_load($nid);

      // Add subject/content to block
      $blocks['subject'] = t('Last Node Created');
      $blocks['content'] = theme('YOURMODULE_node_last', $node);
      return $blocks;
  }
}

/**
 * Implementation of hook_theme()
 */
function YOURMODULE_theme() {
  return array(
    'YOURMODULE_node_last' => array(
      'arguments' => array('node' => NULL),
    ),
  );
}

/**
 * Create the HTML output for last created node
 *
 * @param $node
 * Node object for last created node
 */
function theme_YOURMODULE_node_last($node) {
  // Insert theming code here...
}

For more information on creating custom modules, see the Module developer's guide.


commerce unique identification number for each item on each transaction

prepend your unique id with the order number. Since it's already unique within the order, and presuming an order number is unique, [order-number]-[unique-id] should return a truly unique value with the added benefit of being traceable since the order number would have a searchable or reference-able value.

EDIT:

Further research yielded the module Field default token

This module enables to use tokens as field default values.

Using this you should be able to create the order-ID combination (or any other combination). To prevent user tinkering, I would also suggest Field Permissions:

The Field Permissions module allows site administrators to set field-level permissions
to edit, view and create fields on any entity.


Where I can find examples of Drupal bootstrap levels?

The JS module is specifically for this. It allows you to create ajax callback that only bootstrap to a level you specify via a hook_js().

So you could either use this module or take a look at its code to see how it works.

Good blog post about it HERE


I get notification for TB Sirate Starter update despite that I use new fresh drupal installation

Despite not using the distribution any more I keep getting the message to update TB Sirate Starter

====================================

I had this issue before and yes, I took notes.
In my case it was solved by finding the culprit(s). They were jquery_plugin and jquery_update

# grep -r "tb_sirate_starter" .
./sites/all/modules/jquery_plugin/jquery_plugin.info:project = "tb_sirate_starter"
./sites/all/modules/jquery_update/jquery_update.info:project = "tb_sirate_starter"

The fix / workaround?

I deleted the directories jquery_plugin/ and jquery_update/

Then reinstalled them.

# grep -r "tb_sirate_starter" .
#

No more messages "Update Available - TB Sirate Starter "
And I think this is what the OP asked :)


How can I prevent a custom block from rewriting HTML?

Try going to Admin menu > Configuration > Content authoring > Text formats and editors then edit yours (E.g. "basic html")
Down towards the bottom you should see an option: Correct faulty and chopped off HTML - uncheck that option and save.
Not sure why a widget would expect an un-closed <div /> tag though.


Does 'aggregate and compress CSS files' actually use gzip?

There is a difference.  You are seeing aggregated (ie, concatenated) and minified CSS when you tick that option on the performance page.

That YSlow report is talking about the webserver sending the results compressed responses the wire.  I honestly can't remember if there is a Drupal option for output compression as I always use mod_deflate rules to do this.

Typically, I add the rules directly to the Apache config for my whole server (so I don't have to worry about core updates nuking my .htaccess file).  Lately, I have been using the rules from HTML5 Boilerplate:

<IfModule mod_deflate.c>
  # Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
  <IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
      SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
      RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
    </IfModule>
  </IfModule>

  # HTML, TXT, CSS, JavaScript, JSON, XML, HTC:
  <IfModule filter_module>
    FilterDeclare   COMPRESS
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/html
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/css
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/plain
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/x-component
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/javascript
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/json
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xhtml+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/rss+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/atom+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/vnd.ms-fontobject
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/svg+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/x-icon
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/x-font-ttf
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $font/opentype
    FilterChain     COMPRESS
    FilterProtocol  COMPRESS  DEFLATE change=yes;byteranges=no
  </IfModule>

  <IfModule !mod_filter.c>
    # Legacy versions of Apache
    AddOutputFilterByType DEFLATE text/html text/plain text/css application/json
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE text/xml application/xml text/x-component
    AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml application/atom+xml
    AddOutputFilterByType DEFLATE image/x-icon image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype
  </IfModule>
</IfModule>

Note that this works on MIME type, and not file extensions, so more respones from Drupal will get compressed.


Your temporary directory holds files before they actually move to the appropriate position in your files directory.

Not sure but I think one the example can be the time we upload a file in a content type it first goes to tmp directory before you actually save the node. Also you might have image cache working if file type is image so the file must exist on server before it crops or scale, so tmp is that directory.

Also the tmp folder is always need to be in drupal root directory, the place is configurable from settings.


What is the proper way to handle drupal_get_destination and drupal_goto?

Drupal automatically uses destination, you don't have to do anything. If a destination argument is given, it will override default. So you can simplify your code to a simple, hardcoded $this->redirect(...).

The only exception is when you have links that you want to respect destination too (e.g. a cancel link on a confirm form), then you have to do it yourself. But the default confirm form already does that too AFAIK.


How to retrieve Apache Solr's current search filters?

Sounds like you're writing a module to do this?

If so, if you're implementing something like the apachesolr_query_alter(&$query) hook or something like that, which gives you access to the search query, you can use

function [getFilters][1]($name = NULL)

Note that the name parameter is optional: Returns all filters matching $name, if set; otherwise, returns all filters.


How to reorganize drupal sites/all/modules structure without symbolic links?

The Registry Rebuild module really is the answer. I struggled to solve this problem for hours, then this module fixed it completely, and with elegance!


How can I have Devel generate nodes with different terms and not always the same term?

This happens when you have a default term chosen for the content type.

If you remove the default, it will then randomly choose terms that already exist (if they exist) or randomly generate terms if the vocabulary allows it.


When switching themes in blocks, theme stays the same

Ended up using hefox's (from Drupal comments) fix

<?php
function realname_user($op, &$edit, &$account, $category = NULL) {
    global $theme;
  if (!$theme) return; // prevent realname from overiding theme on block pages
?>

I did add in my own code as a safeguard, in the if statement, the condition that we were on the blocks page.


Creating facets for custom contents added by CCK in apache Solr module

I was finally able to get this done with good assistance from one of the module's maintainer.. This is the issue list query comprising further details and some sample code. Hope this servers of some help to anyone using solr search.

Cheers!!


Database general error: 2006 MySQL server has gone away

9 times out of 10 this error is caused by an insufficiently large max_allowed_packet setting in your MySQL server's my.cnf file.

The standard default for MAMP in my experience is 1M, which isn't usually enough for Drupal (especially considering the size of some of the cache strings it generates).

Try increasing that setting gradually to see if the error disappears. I'm sure a quick google search will tell you how to do that in MAMP.


What about using entity reference (included in D8) ? In your case, Each "department" has "county" and each "staff" has "department" : you may just add field to your department and staff content type (or taxonomy term depend on what you need to do with these).
Your may use pathauto to generate the URL you need for each content type :

county/{county_nid}
county/{county_nid}/department/{department_nid}
county/{county_nid}/department/{department_nid}/staff/{staff_nid}

This can be easylly used with views / content type display mode and could imho fit all your needs.


How to get only the first value of a field in a Views template

When editing the view, there's an option for Multiple field settings. By default view is going to set it up to Display All starting at zero.

You can easily change it to display 1 starting at zero. This will only show the 1st image now.

Hope this helps.


Weird gibberish characters appearing on bottom of Drupal 7 pages

Since these characters appearing within certain section of the website, you need to identify the source of it and which rendering element is responsible for it (either template file or some function).

The easiest way would be to track it down by enabling theme_debug variable in your settings file which enable you to debug the output of the rendering engine.

So please add this line into your settings file:

$conf['theme_debug'] = TRUE;

then refresh the page and check the source code to see which rendering element is outputting this.

For more advanced solution, use PHP debugger such as phpdbg (in PHP >=5.6 core) or XDebug (which allows you to generate a trace file and find the source of the problem). Here is sample xdebug.ini config, so in your scenario you just need to enable xdebug.auto_trace, generate a trace file for single page load, then disable the setting (since it hugely impacts the overall performance). Then open a generated trace file, look for gibberish where they've started to appear and find out which code is generating it.


Am I able to populate an entity form text field with a value from a URL link on an external site

Yes. Checkout the Field default token module. It lets you substitute tokens in place of a field's default value. In your case you want to use [current-page:query:var] for your field's default value. This will let you send someone to the URL http://example.com/my_entity_form?var=DEFAULT which will pre populate the field with DEFAULT.


Adding Pagination to to custom form block results

/**
 * Implements hook_block_info().
 */
function custommodule_block_info() {
    $blocks = array();
    $blocks['latest_news'] = array(
        'info' => t('Latest News'),
        'cache' => DRUPAL_NO_CACHE,
    );

    return $blocks;
}

    /**
 * Implements hook_block_view().
 */
function custommodule_block_view($delta = '') {
    $block = array();
    switch ($delta) {

        case 'latest_news':
            $block['subject'] = t('');
            $block['content'] = latest_news();
            break;
    }
    return $block;
}

/*
 * Implementation of hook_theme
 * */

function custommodule_theme() {
    return array(

        'latest_news' => array('variables' => array('data' => array()),
        'template' => 'latest_news'),

    );
}

    function latest_news() {
     $query = db_select('node', 'node');
    $query = $query->fields('node', array('nid'))
            ->condition('node.status', 1) //Published.
            ->condition('node.type', 'auction_news');
    $query = $query->extend('PagerDefault');
    $result = $query->limit(20)->orderBy('node.created', 'DESC')->execute()->fetchAll(PDO::FETCH_ASSOC);
    $paging = theme('pager');

    return theme('latest_news',array('data' => $result,'paging'=>$paging));
}

In a tpl file latest_news.tpl.php

    <?php
    foreach($data as $lat_news)
    {

       echo '
'.$lat_news->nid.'
';
    }
    ?>

<?php echo $paging;?>


How to restrict one exposed filter per content area?

There is a module that seems to do exactly that: MEFIBS - More exposed forms in blocks.

Apart from that you could follow a workaround mentioned on that module project page where you clone your Views Display, don't change the Path, only change the Exposed settings. You will end up with two different blocks that can be placed in different regions, but working on the same Views page.


How to update a node after loadByProperties?

Assuming you response array will contain one node as suggested by the variable name $profileNode

here is a suggestion to make it :

$profileNode = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->loadByProperties(['field_user_id' => $id]);
// Get the node object.
$profileNodeObject = reset($profileNode);
if ($profileNodeObject) {
  // Make the changes we want : per example set the author to user 4.
  $profileNodeObject->setOwnerId(4);
  // Save the changes.
  $profileNodeObject->save();
}


Drupal 6.x vs 7.x for Multiple Domains and LDAP

This one is easy: go with 6.2.x!

Despite being new and exciting and all of that, Drupal 7 still is very lacking in the stable contrib department. Also, despite the huge number of modules that adopted the D7X pledge, a lot of important and frequently-used modules still don't have stable versions (ahem, Views! say what you want - "beta" and "dev" are not stable enough for enterprise purposes)

Drupal 7 also introduced some API changes that, despite not being huge, still mean that there's a small new learning curve to developing Drupal 7 modules.

Drupal 6, on the other hand, is more than stable and has plentiful offerings for modules including LDAP integration and anything else you might need. Since it's been around for a couple years now, there's no shortage of experienced developers who can aid in implementing the site and developing custom modules.

As far as having to upgrade to Drupal 7 eventually, despite it being a valid point in deciding which version to use, who said you have to be running the latest version? As far as I know enterprises take longer than most to adopt new technologies.

Quite frankly, developing for Drupal 7 (specially large and mission-critical software) is a lot more expensive and complicated at the moment than using Drupal 6 and I would strongly advice against it for at least 3-6 months to wait and see how contrib modules will react and see how it will be adopted in general by the community.


hook_menu and hook_menu_alter are only called when rebuilding the menu table, not on each table load.  So you won't see your print statements.

As a side note, I would use drupal_set_message() rather than print when debugging.


Content Type: Is it possible to have Term reference on Parent Term instead of Vocabulary?

Create a view that show the taxonomy terms that you want to have as options for selection (you will have to manipulate depth).

Then you create an Entity reference field on your content type that references a taxonomy term. When you add the field it will ask for Entity Selection mode. You select Views (the alternative is Simple), and then you select the view that you created above.


How can I find the name of the field store in the DB?

Drupal 7

If the name of the image field is "Dark Image", then the table name in database will be field_data_field_dark_image

Drupal 6

As mentioned in this page, table name should be content_type_YOUR_CONTENT_TYPE_NAME. If the name of the image field is "Dark Image", inside the table you will find a column called field_dark_image that stores field data.


How to restrict access to a path like user/%/flag?

You need to create custom Views access plugin for this.
First, you need to create mymodule.info file with next code

name = Mymodule
description = Custom code
core = 7.x
package = custom
dependencies[] = views
files[] = mymodule_access_plugin.inc

Second, add mymodule_access_plugin.inc in the your module folder  with next code

<?php

/**
 * Access plugin that provides property based access control.
 */
class mymodule_access_plugin extends views_plugin_access {

  function summary_title() {
    return t('Custom access plugin');
  } // summary_title()

  /**
   * Determine if the current user has access or not.
   */
  function access($account) {
    return mymodule_access($account);
  }

  function get_access_callback() {
    return array('mymodule_access', array());
  }

}

Third, implement  hook_views_plugins in your mymodule.module file

<?php

/**
 * Implements hook_views_plugins()
 */
function mymodule_views_plugins() {
  $plugins = array(
    'access' => array(
      'test' => array(
        'title' => t('Custom access check'),
        'help' => t('This is a custom access plugin'),
        'handler' => 'mymodule_access_plugin',
        'path' => drupal_get_path('module', 'mymodule'),
      ),
    ),
  );
  return $plugins;
}

function mymodule_access($account = NULL) {
  global $user;
  if (!empty($account->uid) && $account->uid == $user->uid) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

Fourth, clear caches and apply your custom access plugin in views


EDIT (2015-04-05): Updated the snippet to work with newer version of Views.

Us too had to find the page number of a views result on which a certain node appears, so we can redirect visitors to this page.

By loading a view for a specific display and executing it's query manually, we retrieve an array with all node ids which we can search for a specific node id. When we have got the position of the node id, we divide it by the amount of items per page to get the page number the node is on.

I understand that loading all node ids at once in an array probably should not be done on large amounts of records, but for this exercise it's okay.

/**
 * Custom function to get the page number of a views result a node appears on.
 * Based on Drupal's views_get_view_result().
 */
function yourmodulename_views_get_item_page_nr($nid, $name, $display_id = NULL) {
  $args = func_get_args();
  array_shift($args); // remove $nid
  array_shift($args); // remove $name

  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (is_object($view)) {
    if (is_array($args)) {
      $view->set_arguments($args);
    }

    if (is_string($display_id)) {
      $view->set_display($display_id);
    }
    else {
      $view->init_display();
    }

    // Set the limit to 0 to retrieve all node ID's.
    $view->set_items_per_page(0);

    $view->pre_execute();
    $view->build();

    // Get the views query.
    $query = $view->build_info['query'];

    // Get the return assoc array with return objects, keyed by nids.
    $nids = $query->execute()->fetchAllAssoc('nid');

    // Get position of nid in nids array.
    $index = array_search($nid, array_keys($nids));

    // Get amount of items per page.
    $items_per_page = $view->display[$view->current_display]->handler->get_option('items_per_page'); // As seen at http://api.drupal.org/api/views/includes%21view.inc/function/view%3A%3Aexecute/7.

    // Calculate page number.
    $page_nr = $index === null ? 0 : intval($index / $items_per_page);

    return $page_nr;
  }
  else {
    return 0;
  }
}


I found the best solution to this was using ajax_command_invoke() and layering the required ajax effects together.

For example, you won't be able to directly fade in an element, but you can use replace or prepend, etc., then hide the element, then fade it in.

function my_ajax_callback($form, $form_state) {
  $result = array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace($selector1, $html1), //add your element
      ajax_command_invoke($html1, 'hide'), //hide it
      ajax_command_invoke($html1, 'fadeIn'), //now use the effect you're after
      ajax_command_replace($selector2, $html2), //add your other element
      ajax_command_invoke($html2, 'hide'), //hide it
      ajax_command_invoke($html2, 'show'), //use the other effect
    ),
  );
  return $result;
}


How to make fields available to users in Drupal 7?

Give "Create content" permission to the user type who can create content at your instance.

There is the Field Permission module which lets you specify permissions for each field in a entity. You can set permission for each field by help of this module.


redirecting legacy URLs to corresponding drupal path

I've just done a transition like you mentioned and the domain names changed. I didn't want the old urls hitting my drupal server so I setup a 2nd site just for redirects. At first I had a simple php redirect script that would map old urls to Drupal urls. The mapping came off the "migrate_map" tables that the migrate module generated.

Then someone on the team was concerned about the immediate SEO impact and preferred to keep the old site content available at the old domain name. So I copied the new Drupal site to a 2nd hosting account.

I added a "custom404" module which uses hook_init() to read the URI, detect a pattern, find the unique key in the uri, then lookup the Drupal nid using the migrate_map table and then use drupal_goto() to do a 301 to Drupal URI.

On that Drupal site I show a "website has moved" message with a link to the same URI on the new domain. Pretty soon I'll change my script to just 301 redirect to the new domain directly.

I was initially toying with the idea of using a lower bootstrap level (to have faster redirects) but ran into issues with database connections. Got some great help here about that.


https://www.drupal.org/project/webform_countdown
Provides a textarea component for Drupal webforms with a configurable, twitter-style dynamic word or character count.


Multigroup field in view only showing single delta

OK, to get this to work on Drupal 6, CCK 3 and Views 2, I spun up a testbed on the ever trusty Pantheon and created a content type:

and then created three nodes, the first one had two sets of name/biz/email, the second had one and the third had three.

I then created a View:

with these results which I hope is what you were after.

Things that needed to be done differently:

One.  Add in that Content multigroup filter.  I just chose 'Name' as the field to join on.

Two.  Turn off all grouping of the Fields, eg uncheck this in their setup:

Three.  Put all the values in the Global Custom Text field:


how to give edit permission content to new user in drupal?

If there is only a single user that will have permission for a given company node, you can assign them as the author of the company node and give them the "edit own company nodes" (or similar) permission.

If there are multiple, it's going to be trickier, you could for example add a hidden user reference field to the company node (which only you can edit, with a field permission module) and use http://drupal.org/project/nodeaccess_userreference. Or use http://drupal.org/project/content_access, which allows to configure permissions for single users directly.


The Drush Search and Replace plugin may be of some use

This drush plugin performs a text search & replace on all content and content revisions in all text fields and all custom blocks on a Drupal site.
It does this directly in the database, not by loading, editing and then saving entities, so it is very fast. This also means you should clear the Drupal caches after you run this command.

Hopefully it goes without saying you should give this a dry run before applying it to a live site, how well it works will depend on exactly what data you have in the fields.


Mini panels allows you to use layouts, so you can have rows and columns within a mini panel block. Making life way easier when it comes to applying css.

In addition, it allows you to attach other things, such as views, other blocks, etc..
In contrast, if you use a regular block, you can only do one thing at a time with them.

So if you have lots of blocks, it can be messy if you want to change the block position. While if all the blocks are inside a mini panel, you can move them all at once.

Don't think of it as mini panel vs block. Think of it as mini panel being a block management system.


How to use jquery ui tooltip in Drupal7?

Try adding:

drupal_add_library('system', 'ui.tooltip');

in your theme template.php file

/**
 * Implements hook_preprocess_html
 */
THEME_preprocess_html(&$variables){
  drupal_add_library('system', 'ui.tooltip');
}

That should ensure the library is available. You can add various conditions to make it page specific as required.


Here's what you need:

'#states' => array(
    'visible' => array(
        ':input[name="field_star_rating"]' => array(
            array('value' => t('5')),
            array('value' => t('4'))
        ),
    ),
),


Language Manager getCurrentLanguage returns default language instead

The method you've quoted is the default code for single language sites. For multilingual sites the default LanguageManager is replaced with ConfigurableLanguageManager and the method is overridden wtih this content:

ConfigurableLanguageManager::getCurrentLanguage:

public function getCurrentLanguage($type = LanguageInterface::TYPE_INTERFACE) {
  if (!isset($this->negotiatedLanguages[$type])) {

    // Ensure we have a valid value for this language type.
    $this->negotiatedLanguages[$type] = $this
      ->getDefaultLanguage();
    if ($this->negotiator && $this
      ->isMultilingual()) {
      if (!$this->initializing) {
        $this->initializing = TRUE;
        $negotiation = $this->negotiator
          ->initializeType($type);
        $this->negotiatedLanguages[$type] = reset($negotiation);
        $this->negotiatedMethods[$type] = key($negotiation);
        $this->initializing = FALSE;
      }
      elseif ($type == LanguageInterface::TYPE_INTERFACE) {
        return new Language([
          'id' => LanguageInterface::LANGCODE_SYSTEM,
        ]);
      }
    }
  }
  return $this->negotiatedLanguages[$type];
}

Then the result depends on the language negotiators you have configured in language detection, see comment from @Clive.


Drop-down select instead of selection box in custom field widget

Okay, I figured it out and it was much easier than I thought... It's the "size" attribute. I deleted the size attribute, ('#size' => 12,), and I have a drop-down select list. I suppose it just came to posting the question here for me to figure it out on my own. :P


seems you need to create a "taxonomy view" (category) then create a listing and sort them by the "points" field value.


You can not change existing charge to subscription. It is not a trivial task, but doable by using such modules as Commerce Recurring or  Commerce License and Commerce License Billing.


There are at least three possible issues that I can see:

You are probably not prefixing the function with the right string.
If the module/theme name is m2f_password, then m2f_password_reset_form_alter() is not recognized at implementation of hook_form_alter().
If you are trying to alter the form that is shown at user/password, you should not check $form['#action']; you should implement hook_form_FORM_ID_alter(), and write a function called m2f_password_form_user_pass_alter(). (I assume the short name of the module/theme is m2f_password; if it is not correct, replace m2f_password with the short name of the module/theme.)
user-pass is not a valid form submission callback name: PHP functions cannot contains hyphens. You are then defining m2f_password_redirect(), and that seems a form submission callback.
The correct code is probably the following one.

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


You can have a node reference for players. In node reference you can limit the list of options to a view. You can make a view that has a custom argument that looks up players from the home and away teams already attached to the node.

You might get a better answer for this, but throwing this one out there in the few mins I have.


I want to display the all true/false questions in same page using quiz module. Is it possible?

Try using  Quiz Progress module .. It offers nice User Experience to track status of questions and navigation..
Project page says

Quiz 6.x has the limitation of displaying only one question at a time.
This makes it hard to navigate from one question to other especially
when you have a skipped question in the beginning and you have your
current question at the closure of quiz.
The "Quiz Progress" module tries to overcome this problem, it provides
a block that prints the list questions in the quiz referenced by title
or number (with tooltip) depends on the widget configured in module
settings, highlighting their status skipped, answered or unanswered as
a link.

Here is the final output using above module which lists all questions...

If you are looking for Solution from Quiz Module itself take a look at this issue in Quiz Module.. Seems like #106 works in above issue..


How set specific input format for specific field like in Drupal 7?

The way I recently did this on a Drupal 8 site was to use Better Formats.

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

You can force filter format per field - one option = no select box. Even for admins.

If you are using Paragraphs, you will also need this patch.


With all due respect, I think Webform is the wrong way to approach this.  Drupal core can be configured to handle registration in the manner you are requesting with less workload for your site admins (no manual registration of webform data).

On  Administration >> Configuration >> People (admin/config/people/accounts):

Set Who can register accounts? to Visitors, but administrator approval is required

As for the fields in the Webform (first name, last name, e-mail, company, etc.), you should create those on the Administration >> Configuration >> People >> Account settings page (admin/config/people/accounts/fields) under the Manage fields tab.  Make sure to mark the fields as required and to display them on the registration form.  Note that storing these fields as part of the user account will cause all of this information to be displayed in the user profile.  If you need field-level control of the information (to make last name private/hidden, for example), you can use the Field permissions module.
edited per Berdir's comment By default, Drupal will send an e-mail to the site administrator when an account is registered.  If you need a special notification, you can use the core Trigger and Actions modules (or the contributed Rules module) to set up an action (or rule) to e-mail the administrator(s) when a new account is registered and pending approval.


Sounds like this may be solved by using aggregation

Change the No to Yes.


No need to change the id, i am printing the region not the block, just change the block from secondary menu region and will print the new block.


Very slow cache processing: Is there any alternative?

If a large part of your time is spent with serialize then that might point to some broken code; as in things keep getting serialized to be stored in the cache/db but it keeps on having a cache miss, otherwise you should only see unserialize with heavy cache usage.

The pattern you're pointing to sounds like you have some code that is abusing the variables table. Inside variable_initialize() it runs array_map with serialize, and variable_set() calls serialize. I would check the max_allowed_packet value inside of MySQL; my preference is to set it to 32M.

If you can provide more details, I can give you a better answer. I will say that using PHP7 should give you a big speedup if you haven't done so.


Exclude taxonomy term from view display except its own?

You seem to be on D7 and using the default Taxonomy term Views.

Out-of-box Taxonomy term Views is set up to cover all taxonomy Vocabularies you create on your site.

You can override this to "split" that functionality into more than one View, that have different settings, and control which Views is responsible for displaying which Term pages.

BTW I find it best to disable the original Taxonomy terms view, Duplicate (Clone) it and work on the Duplicate so I always have the original to reference back to.

On D7 this is usually done with the help of the Taxonomy display module although this module only provides a convenient interface for adjusting each term, but it doesn't provide the "splitting" on the Views level.

You'll have to create the second View yourself, and edit the original Taxonomy term views to exclude that special term yourself.

In the original Views you can add another Contextual filter, set it to the fixed value of the ID of your xyz term, and under More set to Exclude. This way no articles tagged with this term will appear on other term pages.

Clone the Taxonomy terms Views, name it meaningfully, and override values for the Contextual filter to only show content for the xyz term (I'm guessing ti will again be the fixed default value, but without Exclude).

You mention regions and themes a lot, but that is not how you usually control filtering in Views. So if you have more than one View listing content where you want to exclude the special xyz tagged content, you'll have to edit each view to filter out that content. There is no easy way to filter according to theme regions that I'm aware of.


Working with Drupal autocomplete form is good, instead of using the jQuery autocomplete.

Here we have a solution that how to create a custom autocomplete form and to get the user names or whatever.

I am giving the simple example of using it.

Take a menu item in hook_menu to get the autocomplete form. This will call the function called test_autocomplete_form.

$items['autocomplete_form'] = array(
        'title' => 'Test autocomplete form',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('test_autocomplete_form'),
        'access arguments' => array('access test autocomplete'),
        'type' => MENU_NORMAL_ITEM
);

// Which will get the autocomplete form
function test_autocomplete_form(){
    $form = array();
    $form['testauto'] = array(
        '#type' => 'textfield',
        '#autocomplete_path' => 'test/autocomplete',
        '#description' => t('Please type any letter.'),
    );
    return $form;
}

We have to mention our custom path in for the #autocomplete_path attribute. Here I have given a path like test/autocomplete which will have to get the autocomplete result for that need to have one more menu item with the same path which we have given for the #autocomplete_path:

// menu item to get the autocomplete result,Which will call the function called 'test_autocomplete'
$items['test/autocomplete'] = array(
        'title' => 'Test autocomplete',
        'page callback' => 'test_autocomplete',
        'access arguments' => array('access test autocomplete'),
        'type' => MENU_CALLBACK
);

// function to get the autocomplete result, I am taking the user table to get the users names in the autocomplete field
    function test_autocomplete($string = '') {
      $matches = array();
      if ($string) {
        $result = db_query_range("SELECT name FROM {users} WHERE LOWER(name) LIKE LOWER('%s%%')", $string, 0, 10); // only 10 results will show
        while ($user = db_fetch_object($result)) {
          $matches[$user->name] = check_plain($user->name);
        }
      }
      drupal_json_output($matches); // Returns the data in JSON format
    }


Get the url for an images in a Field Collection for the Node Template

You can find a good example of how to decompose the field_collection with a foreach in drupal.org

https://www.drupal.org/node/1155752#comment-12170687

if (isset($node->field_gallery_images)) {
  $nodeField = field_get_items('node', $node, 'field_gallery_images');
  if (!empty($nodeField)) {
    foreach ($nodeField as $key => $item) {

      $field_collection_item = field_collection_item_load($item['value']);
      $item_wrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);

      print '
';
      $field_image = $item_wrapper->field_gallery_image->value();

      print theme('image_style', array('style_name' => 'large', 'path' => $field_image['uri']));
      print '
';
  }
}


Give your submit button a unique and valid #name attribute. I don't think it will work if you put spaces in it:
$form['actions']['save'] = [
  '#type' => 'submit',
  '#name' => 'standard-save',
  '#value' => t('Print and Mail Check'),
  '#button_type' => 'primary',
  '#submit' => [
    '_my_module_form_submit',
  ],
];

Submit handler
function _my_module_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  \Drupal::messenger()->addStatus(t('Standard Save button triggered.'));
}


What's the best way to put in a link to a translated node in a D8 template?

The easiest method of providing language switching links would be using the language manager's getLanguageSwitchLinks() method. However, this might - depending on your language settings - also provide fallback links, if the node is not translated to the target language. An abstract example:

use Drupal\Core\Language\LanguageInterface;

function THEME_preprocess_node(&$variables) {
  $node = $variables['node'];

  $language_manager = \Drupal::languageManager();
  $current_language = $language_manager->getCurrentLanguage()->getId();
  $links = $language_manager->getLanguageSwitchLinks(LanguageInterface::TYPE_CONTENT, $node->toUrl());

  $variables['current_language'] = $current_language;
  $variables['translations'] = [
    '#theme' => 'links',
    '#links' => $links,
    '#set_active_class' => TRUE,
  ];
}

For your use case - to show links to translated content only -, your approach to using getTranslationLanguages() of the TranslatableInterface is on the right track.

But be aware, that it will return entity translation instances also for non-published - or otherwise limited - content translations, to which the current user may not have view access to. Hence, he will get an "Access denied" error after clicking the links.

Additionally, the code should be generic enough to allow for further languages being added using the admin UI in a later stage of the application's life-cycle, without having to touch your preprocessing/templates anymore.

Therefore some suggested improvements for your solution:

Check, whether the current user has access to the translation.
Avoid using hard-coded language identifiers. As I suppose you did so to not add further links for the current language, you should use your $current_language variable to do the checks.
Avoid using hard-coded language link labels. Consider using \Drupal\Core\Language::getName() instead.
Use a list of language links instead of a dedicated variable for each language, and pass that list to the template. This way you can just iterate over the links.
Don't return markup (the links) from within your preprocess hook, but allow creating the links within the templates.

This sums up to something like this:

use Drupal\Core\Template\Attribute;

function THEME_preprocess_node(&$variables) {
  $node = $variables['node'];

  $language_manager = \Drupal::languageManager();
  $current_language = $language_manager->getCurrentLanguage()->getId();

  $links = [];
  foreach ($node->getTranslationLanguages() as $langcode => $language) {
    // Skip any translation that cannot be viewed.
    $translation = $node->getTranslation($langcode);
    if (!$translation->access('view', NULL, TRUE)->isAllowed()) {
      continue;
    }
    // Get URL of the translation.
    $url = $node->toUrl('canonical')
      ->setOption('language', $language)
      ->setAbsolute()
      ->toString();
    // Optionally provide an 'active' class.
    $classes = [];
    if ($langcode == $current_language) {
      $classes[] = 'active';
    }
    // Construct information for a link.
    $link = [
      'language' => $langcode,
      'is_current' => $langcode == $current_language,
      'url' => $url,
      'title' => $language->getName(),
      'attributes' => new Attribute(['class' => $classes]),
    ];
    $links[] = $link;
  }

  $variables['current_language'] = $current_language;
  $variables['translations'] = $links;
}

In your template, you can then create the links like this:

{% if translations %}
  {% for item in translations %}
    {# Optionally skip current language #}
    {% if not item.is_current %}
      {{ item.title }}
    {% endif %}
  {% endfor %}
{% endif %}


Migrate users from a custom application DB into Drupal

Yes. The Migrate module does exactly just that.

You just need to write a migration script, which is comprised of the source (there's a lot of plugins out of the box like MySQL, CSV, JSON), the destination (there's already a User class you can extend from), and the mapping (the mapping of source fields to destination fields).

Drupal will probably have a different hashing mechanism that your CMS, so the passwords probably cannot be reused. The values can be copied as is, and just force your users to reset their passwords. There's also the Force Password Change module for that.


Display content based on taxonomy with view

You would use /taxonomy/term/% - which is a default view, you don't have to create it. The view should show Fields of body content or whatever other fields you you have associated with the node that you wish to display.
Your content types also need to have fields where the correct taxonomy categories can be selected when creating the node.
Your view "Sort" and "Filter" criteria will determine how these nodes are ordered.

To preview your view, use /numerical term ID of your taxonomy term

To get your nodes to display, create a menu with the same parent-child structure as your taxonomy terms and set the menu paths as the taxonomy term ID. You would then display this menu as a block either on a page or in a sidebar.


go to sites/default/services.yml

and write in the proper indentation with spaces as below..

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

*remember to follow the same structure as above

If not working clear cache from back-office :
http://your-drupal.com/admin/config/development/performance


Do not request a billing address during checkout

It is quite hard to do indeed. One way to do this is by setting a dummy billing address and hide the address form.

You will need to do the following:

In a custom module, add a CommerceCheckoutPane plugin. The plugin class should extend \Drupal\commerce_payment\Plugin\Commerce\CheckoutPane\PaymentInformation.
Override the buildPaneForm() method, in there:

Set an #after_build callback. In this callback, make each address field non-required. The reason that you need an #after_build callback is that else address fields won't be available.
On the commerce_profile_select element, set an #element_validate callback. In this callback, set the address values. The reason that you need an #element_validate is because a general form validation callback is called too late in the validation process to set the address in time. This is because the address element has a constraint and the address is validated against this constraint after #element_validate and before a general form validate. Should you try to set the address in a general form validation callback, then you'll get address field required errors because of the constraint.

You can set the #element_validate callback as well in the #after_build callback, which I've done in the code example below.

To hide the address form, you'll need to set #access to FALSE for the address form. This needs to happen in the #after_build callback as well, because earlier the address form isn't available yet.
On the checkout flow settings, disable the default Payment information pane (and enable the custom Payment information pane if not yet enabled).
To hide the dummy billing address on the 'Review' step, copy the template commerce-payment-method--credit-card.html.twig (and/or commerce-payment-method.html.twig if you are using a non-credit card payment method) to your theme and remove the line {{ payment_method.billing_profile }} from it.

Code example (file name: mymodule/src/Plugin/Commerce/CheckoutPane/PaymentInformation.php):

namespace Drupal\custom_commerce\Plugin\Commerce\CheckoutPane;

use Drupal\commerce_payment\Plugin\Commerce\CheckoutPane\PaymentInformation as PaymentInformationBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;

/**
 * Provides the payment information pane.
 *
 * @CommerceCheckoutPane(
 *   id = "custom_commerce_payment_information",
 *   label = @Translation("Custom Payment information"),
 *   display_label = @Translation("Payment information"),
 *   default_step = "order_information",
 *   wrapper_element = "fieldset",
 * )
 */
class PaymentInformation extends PaymentInformationBase {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $pane_form = parent::buildPaneForm($pane_form, $form_state, $complete_form);

    // Add an after build callback in order to make modifications on the address form.
    $pane_form['#after_build'][] = [$this, 'paneFormAfterBuild'];

    return $pane_form;
  }

  /**
   * After build callback for the pane form.
   */
  public function paneFormAfterBuild(array $pane_form, FormStateInterface $form_state) {
    // Get billing form element. Where it is located depends on the payment method that is chosen.
    if (isset($pane_form['add_payment_method']['billing_information'])) {
      $billing_form = &$pane_form['add_payment_method']['billing_information'];
    }
    elseif (isset($pane_form['billing_information'])) {
      $billing_form = &$pane_form['billing_information'];
    }
    else {
      // No billing information found.
      return $pane_form;
    }

    // Get the address form element.
    $address_form = &$billing_form['address']['widget']['0']['address'];

    // Add element validation callback to autofill the address.
    $billing_form['#element_validate'] = array_merge(
      [[$this, 'profileSelectValidate']],
      \Drupal::service('element_info')->getInfoProperty('commerce_profile_select', '#element_validate', [])
    );

    // Set all address fields to non-required.
    foreach (Element::children($address_form) as $key) {
      $address_form[$key]['#required'] = FALSE;
    }

    // Hide the address form.
    $address_form['#access'] = FALSE;

    return $pane_form;
  }

  /**
   * Element validation callback for the profile select element.
   */
  public function profileSelectValidate(array &$element, FormStateInterface $form_state) {
    // Set dummy address.
    $address = [
      'given_name' => 'A',
      'family_name' => 'A',
      'address_line1' => 'Dummy street',
      'postal_code' => '1234 AB',
      'locality' => 'Dummy city',
      'country_code' => 'NL',
    ];
    $form_state->setValue($element['address']['widget'][0]['address']['#parents'], $address);
  }

}


Is there a way to pass many arguments and not have an ugly url?

You could use form submission or cookies to store values, but neither of these are a particularity good ideas.

I would recommend (if you don't like the URL showing) using AJAX to retrieve/update the graph. You still have the ugly url but you hide it inside the ajax request.

So your module displays

/mypath

but the request could be

/mymodule/displaygraph/x/as/32432/s///


How can I fix a pager limited to 2 pages?

You can set items per page for the Home page at Configuration/System/Site information/FRONT PAGE as shown in following image:

And you can check also how many nodes you have promoted to the frontpage  at Admin/Content. So these two settings will allow you set all this. Hope this will work.

Additional:

If you want more settings for the FrontPage, you can go to Admin/Structure/Views/ and you can see a view named FrontPage, that is by default disabled. But you can enable. And that view works as a FrontPage. So in views setting you can set as you want.


Disable page compression only on specific pages

You're probably looking for something like the CacheExclude module? Here is a quote about it (from the module's project page):

  ... provides a simple way to exclude certain pages from being cached. Sometimes you want all pages to be cached for anonymous users except for one or two pages that have dynamic or random or rotating content. If those pages are cached, the dynamic parts cease to be dynamic. This module allows an administrator to selectively exclude certain paths from being cached so that dynamic content is actually dynamic.


How do I add a user as a field in Drupal 7?

Is this what you need?

Add a field to the File content type.  For FIELD TYPE choose "Entity Reference".
Save and configure the new field.  For Target type choose "User".


$nid = 1; // lets pretend the node ID you want to redirect is 1.

$url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $nid]);
$form_state->setRedirectUrl($url);


How to make a page visible only to users with permission to use the administration theme?

There are some modules that can help with this: like Content Acess, or Node Access

Node Access
Content Access


IEF has a hook as outlined in the inline_entity_form.api.php file.

/**
 * Perform alterations before an entity form is included in the IEF widget.
 *
 * @param $entity_form
 *   Nested array of form elements that comprise the entity form.
 * @param $form_state
 *   The form state of the parent form.
 */
function hook_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  if ($entity_form['#entity_type'] == 'commerce_line_item') {
    $entity_form['quantity']['#description'] = t('New quantity description.');
  }
}

Check the inline_entity_form.api.php file as there are a few hooks that you may be able to use.


Why does #triggering_element pick the wrong element?

The problem is in form_builder() where it fallbacks to the first button if no button can be found.

A comment from form_builder():

// Therefore, to be as consistent as we
// can be across browsers, if no 'triggering_element' has been identified
// yet, default it to the first button.
if (!$form_state['programmed'] && !isset($form_state['triggering_element']) && !empty($form_state['buttons'])) {
  $form_state['triggering_element'] = $form_state['buttons'][0];
}

More info can be found here: https://www.drupal.org/node/2546700#comment-11164091

There is also a patch for this problem that can be found in the link above.


Creating a website with search filters like amazon and Ebay. Is it possible?

You can use something like Solr as that supports faceted searching.

It is rather complicated to set up though if you are using your own search server.


Are node data stored in the render array $page?

Yes, it's probably in there somewhere. However, it much easier to get the current node object (if there is any) with the menu_get_object() function:

if ($node = menu_get_object()) {
  // Do stuff with $node.
}


Yes, you can use

#limit_validation_errors

  Used by: button, image_button, submit

  Description: Provides an array of sections which are parts of
  $form_state['values'] which should be validated, implying that
  sections which are not listed should not be validated.

  This is normally used in multistep forms in the case of a "back" button, for
  example, where '#limit_validation_errors' => array() would mean not to
  validate anything as form values on the current page are to be
  discarded anyway.

  #limit_validation_errors does not have any effect if #submit is not set. More discussion is in the form_set_error() documentation.

  Values: array indicating sections of the $form_state['values'] which should be validated.


How to set in my own module dependency on a composer package?

You can add dependencies in your module.

Navigate to your module's root folder. Run composer init. When you get to the question Would you like to define your dependencies (require) interactively, say yes. You can then declare any composer libraries your module depends on.

You can also manually create a composer.json file that looks something like this:

{
    "name": "uniquenamespace/packagename",
    "description": "This module does some stuff",
    "type": "drupal-module",
    "authors": [
        {
            "name": "Some Guy",
            "homepage": "https://www.example.com/some_guy",
            "role": "Maintainer"
        }
    ],
    "require": {
        "somevendor/somepackage": "^1.9"
    },
    "license": "GPL-2.0-or-later"
}

Run composer validate to check that your composer.json file is valid.


How to pre-populate a text field when creating a new node?

instead of $form['field_FIELD_NAME']['und']['#default_value'] you should use
$form['field_FIELD_NAME'][LANGUAGE_NONE][0]['value']['#default_value']
try something like:

$form['field_manager_name'][LANGUAGE_NONE][0]['value']['#default_value'] = 'hello world';
$form['field_manager_email_address'][LANGUAGE_NONE][0]['email']['#default_value'] = "nobody@yahoo.com";


Does securelogin module needs to have a certificate?

Yes, the securelogin module requires an SSL certificate. From the README file:

  Before enabling the module, you need to set up your server to support
   23 SSL.


Contact Form with drop-down subject (bonus: auto-selected based on GET/POST)

You can try hook_node_view() to pre-select default value of webform component on the base of referer.

function yourmodule_node_view($node, $view_mode){
    if($node->nid == [nid of webform]){
            global $base_path;
            $referer = $_SERVER["HTTP_REFERER"];
            $start = strpos($referer, $base_path) + strlen($base_path);
            $ref_local_path = substr($referer, $start);
            switch($ref_local_path){
                    case 'service_1_path':
                            $node->content['webform']['#form']['submitted']['<component_name>']['#default_value'] = 'option_1';
                    break;
                    case 'service_2_path':
                            $node->content['webform']['#form']['submitted']['<component_name>']['#default_value'] = 'option_2';
                    break;
            }
    }
...

If you are looking to do it via JS/JQuery that is another solution.


What is the benefit of Panels Everywhere

My experience with PE (panels everywhere) was great.
I been working for 1 year with PE on a big project and i can say:

The first advantage of PE is the entire layout control. while panels only affect the "content" region, PE get full control of all page including header and footer (which is no possible only with panels).
Second big advantage its the possibility to select variants as layouts letting you decide wich layout (variant) to show on every page taking that decision with the access arguments like a normal panel.

as you can see there are similarities with Omega theme, and in the fact both modules resolves the same issue.


Panels supports cloning/exporting the whole panel page, as well as individual page variants. It doesn't support cloning/exporting individual content panes (afaik)

However, you could potentially do it manually manipulating the panel export code.

e.g:

Export source page with new panes to clone
Copy desired pane definition from code export
Export target page to save into
Copy pane definition back into the desired section of the export code
Reimport the exported target page.

Manual, but something like that would work. You could also do it programmatically with the ctools/panels api.


Programmatically set value of Boolean radio button field in form

First, check you are setting the #default_value property at a correct level in the $form array. It seems quite weird to get multiple values in $form['profile_company']['field_employees']['und'], so I'm not sure about assigning defaults nested under [0]['value'] (but I could be wrong).

A good rule is to ensure you set #default_value at the same level as the #options array. For example, if you would have these options under the lang code like :

print_r($form['profile_company']['field_employees']['und']);

# Output :
Array
(
    ['#options'] => Array (
        # ... => ...
    ),
    # ... => ...
);

... you would set the #default_value at the same level :

$form['profile_company']['field_employees']['und']['#default_value'] = $default_value;

Secondly, ensure the #default_value is mapped to an existing key in the form #options array :

# Let's say your options are defined as :
$form['profile_company']['field_employees']['und']['#options'] = array(
  0 => t('N/A'),
  1 => t('No'),
  2 => t('Yes')
);

# This would set 'N/A' as default :
$form['profile_company']['field_employees']['und']['#default_value'] = 0;


How can I get the user ID from an order?

use Drupal\uc_order\Entity\Order;
$order_load = Order::load($order_id); //Load Order
$ownerinfo = $order_load->getOwner(); //Fetch Owner Info
$ownerID = $order_load->getOwnerId(); //Fetch Owner ID
$ownerEmail = $order_load->getEmail(); //Fetch owner email


Create many to many Relationship with a specific fields in a Content type to taxonomy

You will have to use entity_reference.

Add a field "Core" to your content type of entity reference.
Then under "target type", choose "taxonomy term"
Under "entity selection" choose your vocabularies
On the next page set "Number of values" to "unlimited"


Drupal 6 will not use updated htaccess 301 information

.htaccess shouldn't require any cache flushes, restarts of the server, etc. They should just take effect.

If you want to check to make sure that your editing the right file (and your not on a production server) you can always throw and invalid line in your .htaccess file. If it throws back a 500 error, your editing the right file and something is wrong somewhere in it, if it doesn't your're working on the wrong file.


Your currency symbol is most likely coming from the field definition. Check the "prefix" value for the field in question at admin/structure/types/manage/<content_machine_name>/fields/<field_machine_name> replacing the items in <> as appropriate.


The required regions:

regions[content] = Content
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom

More on this can be found at http://drupal.org/update/themes/6/7#closure


EntityFieldQuery to search Content Type for text and select matching Nodes

Do you mean something like this;

$keywords=$_POST ['keywords'];

$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
->propertyCondition('type', 'product')
->fieldCondition('field_main_category', 'tid', $category, 'IN');

if(isset($keywords)) {
 $query
   ->fieldCondition('field_sku', 'value','%'. $keywords .'%', 'LIKE');
}
$result = $query->execute();

UPDATE

You can do an OR for each of the field. SO to do this you add a tag to the query which you are building and then you can alter the query using the hook_query_TAG_alter

    $keywords=$_POST ['keywords'];

    $query = new EntityFieldQuery();
    $entities = $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'product')
    ->addTag('something');

    $result = $query->execute();

function modulename_query_**something**_alter(QueryAlterableInterface $query) {
  $or = db_or()
    ->fieldCondition('field_sku', 'value','%'. $keywords .'%', 'LIKE')
    ->fieldCondition('field_name', 'value','%'. $keywords .'%', 'LIKE');

  $query
      ->condition($or);
}

This is just and example and you will have to make changes as per your requirements but this OR will definitely help.

Refer to the following links for a good example;
http://treehouseagency.com/blog/tim-cosgrove/2012/02/16/entityfieldquery-let-drupal-do-heavy-lifting-pt-1
http://treehouseagency.com/blog/neil-hastings/2011/09/06/building-energygov-without-views
http://treehouseagency.com/blog/fredric-mitchell/2012/02/21/or-queries-entityfieldquery


Is it safe to truncate a field revision table?

I think there the Field SQL norevisions module will help you out:

  Field SQL norevisions provides a field storage backend that prevents
  entity revisions from being saved to the MySQL storage backend.

  The purpose of the module is to reduce the amount duplicated data that
  is saved on large Drupal sites that do not use revisions. It has the
  additional performance benefit of halving the number of queries during
  creating entities with fields.

This module will not allow revision fields to be created so it will increase your performance as number of queries will get reduced, besides that you will have no revisions on nodes further.

Also you can use some custom module codes provided on following URL:

http://www.ambidev.com/make-your-drupal-7-faster-by-removing-all-revisions/

and this module to delete revision entries:

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


How to toggle price display with and without tax?

Check out commerce price by components module. You can show both prices with and without VAT. If you want to toggle I'm afraid you will have to write a custom module... .


Fixed width for columns in grid view (Views)

I had success with explicitly setting the width of the table that contains the images/titles.

Set the width of <table class="view-view-grid cols-3> to 100% in your CSS and see if that doesn't help.