Since you are using the %uid wildcard in the menu definition, your kidb_profile_redirect_user() is not getting a user ID, but what uid_load() would be returning. That function is not defined from any module and that is the reason why you get the "page not found" error.

The list of wildcards defined from Drupal 6 is reported in Wildcard usage and core's wildcards. A description of what auto-loader wildcards are is given in hook_menu():

  Wildcards in Paths

  Simple Wildcards

  Wildcards within paths also work with integer substitution. For example, your module could register path 'my-module/%/edit':

  $items['my-module/%/edit'] = array(
    'page callback' => 'mymodule_abc_edit',
    'page arguments' => array(1),
  );

  When path 'my-module/foo/edit' is requested, integer 1 will be replaced with 'foo' and passed to the callback function. Note that wildcards may not be used as the first component.

  Auto-Loader Wildcards

  Registered paths may also contain special "auto-loader" wildcard components in the form of '%mymodule_abc', where the '%' part means that this path component is a wildcard, and the 'mymodule_abc' part defines the prefix for a load function, which here would be named mymodule_abc_load(). When a matching path is requested, your load function will receive as its first argument the path component in the position of the wildcard; load functions may also be passed additional arguments (see "load arguments" in the return value section below). For example, your module could register path 'my-module/%mymodule_abc/edit':

  $items['my-module/%mymodule_abc/edit'] = array(
    'page callback' => 'mymodule_abc_edit',
    'page arguments' => array(1),
  );

  When path 'my-module/123/edit' is requested, your load function mymodule_abc_load() will be invoked with the argument '123', and should load and return an "abc" object with internal id 123:

  function mymodule_abc_load($abc_id) {
    return db_query("SELECT * FROM {mymodule_abc} WHERE abc_id = :abc_id", array(':abc_id' => $abc_id))->fetchObject();
  }

You probably meant to use %user, which would return to your page callback the object returned from user_load(). Using that wildcard avoids you check in your code that the user ID is valid (e.g. there is a user account with that ID), but also means that you should change your code to match the following.

function kidb_profile_redirect_user($account) {
  drupal_goto('profile-main_profile/' . $account->uid . '/edit');
}


Warning: explode() expects parameter 2 to be string, array given in menu_node_submit()

The line that is throwing the error is in the core menu.module. The arguments that are getting passed to it are not valid. To troubleshoot it you would have to backtrace what is getting passed to it to see what is malforming the data or not creating proper data in the first place. If you use debug_backtrace you should be able to find where the bad data is originating from.

Specifically $form_state['values']['menu']['parent'] should be a string (to have explode work on it) but at that time, it is an array.


How do I dynamically change the title of a menu link?

You might try hook_preprocess_menu_link()

function MYTHEME_preprocess_menu_link(&$variables) {
    global $user;

    if (isset($variables['element']['#original_link']['menu_name'])
        && $variables['element']['#original_link']['menu_name'] == 'my-menu-machine-name'
        && $variables['element']['#title'] == 'ORIGINAL LINK TITLE') {

        $new_title = (check for gender) ? 'New title 1' : 'New title 2';
        $variables['element']['#title'] = $new_title;
    }
}

Fill in your menu machine name, the title you want to change, the conditional for the gender and the new titles depending on the gender value.


How do I print the term names associated with a node?

You can do this:

foreach($nodes as $node) {
  $categories = $node->field_category->referencedEntities();
  foreach($categories as $category) {
    print_r($category->getName(). ",");
  }
  print("\n");
}


I had to migrate a nested Vocabulary from Drupal 6 to Drupal 7. My Strategy was:

Migrate the plain terms
Use the postImport() of Migrate-API to map the Parent-Relationship

public function postImport() {

// Get alle Terms from features_dd_private_contact_form_subjects
// Query zum Laden der Daten aus Drupal6
$source_query = Database::getConnection('legacy', 'legacy')
  ->select('term_data', 't');

// Join Terms with voab
$source_query->join('vocabulary', 'v', 'v.vid = t.vid');

// Join Hierarchy
$source_query->join('term_hierarchy', 'th', 'th.tid = t.tid');

$source_query->condition('th.parent', '0', '<>');

$source_query->fields('th', array());

$source_query->condition(
  'v.module',
  'features_dd_private_contact_form_subjects',
  '='
);

$source_query->fields('t');

$source_records = $source_query->execute();

foreach ($source_records as $source_record) {

  // Term-ID in destination db.
  $dest_tid = $this->get_destination_tid_by_old_tid($source_record->tid);

  // Parent-Tid in the destination.
  $dest_parent_tid = $this->get_destination_tid_by_old_tid($source_record->parent);

  $child_term = taxonomy_term_load($dest_tid);
  $child_term->parent = $dest_parent_tid;
  taxonomy_term_save($child_term);
}

}


Ubercart shipping quotes are being based on total before discounts

So apparently I needed a good nights sleep.  For anyone else in my situation, advise your client that this is not a good idea.  Why?  Because you WANT the shipping module to calculate the amount of shipping on the final total WITHOUT coupons because you still need to incur the cost of shipping the items.  (head smack)

For example - if I changed it to calculate shipping on the total AFTER the coupon is applied, for all the other shipping methods this might bump the customer down to a lower shipping rate - and the store owner would lose money on the shipping.

My solution - exclude free shipping from carts that contain a coupon and create a new free shipping for carts including coupons with a higher $ amount.  For example instead of being $80 for free shipping it would be $100 for free shipping with carts including a coupon.  It's not a perfect solution, but it's better then screwing up all the other shipping settings.


Markup filtering at theme level (security)

Rather than remembering specific rules about which variables are safe at which point in the process I suggest you just test things out.

If you can execute Javascript by entering it as the title then you know you have a problem. I try each of these two example snippets of javascript when I want to test something:

<script>alert('xss');</script>
<img src="notfound.png" onerror="alert('xss');">

If your sanitization is working properly then you should either see the tags escaped (displayed as >) or stripped (completely removed from the output).

It is also good to understand the internal workings of Drupal so that you know which functions are safe or not, but knowing how to test for XSS will serve you well in dealing with areas where you are unsure or working with something other than the API.


How do I provide a field storage definition for hook_entity_bundle_field_info?

I ran into the same issue. It looks like there might be a problem with Core.

This patch attached to the issue "Hook entity_field_storage_info is broken" fixed things for me.


user warning: INSERT command denied to user

That doesn't really make sense. Drupal is just a PHP application; if you're using exactly the same connection details in Drupal as you are in your stand-alone PHP application, and that works, it's only logical that your Drupal connection will work too.

You've obviously checked that the username and password are correct, but have you checked the Drupal is connecting to the server from localhost? That would be the only other possible difference. If Drupal is connecting from a remote machine then you'll need to grant specific privileges to the user for that specific location.

The easiest way to see what you've already got is to run a SHOW GRANTS query on the database in question. That will show you something like this:

Grants for username@localhost
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER ON *.* TO 'username'@'localhost' IDENTIFIED BY PASSWORD '*xxxxxxxxxxxxx'

Plus a few more more rows more than likely.

Check through those rows to make doubly sure that there is a grant for INSERT for the database user AND the location that the Drupal website is connecting from.

EDIT

You could maybe get around the error using drupal_write_record():

$record = new stdClass;
$record->col1 = 'something';
$record->col2 = 'something';
$record->col3 = 'something';

drupal_write_record('table_name', $record);

But that really shouldn't make any difference


How to handle enabling new modules with Drush via makefile

I worked for a company that had a large dev/stage/prod flow that tried to automate as much as possible.  Everything had to be done in code, scripted either using features or update hooks.

Basically, what you wanting is to have 1 custom module that exists to contain update hooks.  This way, when a developer pulls an update to the code base, they run the db update, and that can perform whatever module enable/disables need to happen.  The update hooks do not affect a new installation, because it is assumed that the module is already up to date when it is installed, and will only execute newer updates.

To summarize:

Continue using your installation profile to perform the necessary installation tasks (enabling modules, etc.).
Use a custom "update" module which uses hook_update_NXXX() to enable/disable new modules and otherwise keep your site's administrative tasks in sync.

Here is a post that talks about a similar approach and gives code examples.


jCarusel + colorbox, show one thumbnail and open different image

Ok, I figured this out and I'm putting answer here for future generations. I realized that my invisible Thumbnail field had set colorbox as formatter. It was blocking Colorbox trigger from working. Silly trap, I hope someone will be able to avoid this mistake because of this.


What is the difference between "Language: Not specified" & "Language: Not applicable"?

Not applicable means that we know that the very concept of Human languages doesn't apply to this textual piece of content. A relevant example for such content would be Binary code.

For more see http://www.w3.org/International/questions/qa-no-language#nonlinguistic.

Not specified means we don't know if the text might or might not include human-language content.

For more see http://www.w3.org/International/questions/qa-no-language#undetermined.

(Both "see more" links are taken from the code documentation in \Drupal\Core\Language\LanguageInterface which explains those constants quite well).

In general, both options makes no difference to how content is displayed, but they let you treat differently to content on your site if you'd wanted to (in views, custom code, ...)


How to print a field in a view only when it appears first?

You can achieve this using the Grouping field setting in the view's Format settings. You will need to be using Fields (as opposed to Content) in the Format section of your view.

In your Fields list, click on the taxonomy term field to open the field configuration. Check Exclude from display and apply:

In the Format section of your view, click on the Format Settings.

The Grouping field Nr. 1 select list is available in each Format type, so no worries if you have it set to HTML list or another format. Change the field from None to the taxonomy field you want to group by and apply.

Your view will now show products grouped by the taxonomy term. From this point you can use the Sort criteria of the view to get the ordering of products or taxonomy terms you need.


Must new tables be created in hook_update_N()?

So just a copy paste from drupal.org. You also need to add the schema definition to hook_schema.

/**
 * Create new database table {mytable2}.
 */
function mymodule_update_7101() {
  $schema['mytable2'] = array(
     // table definition array goes here
  );
  db_create_table('mytable2', $schema['mytable2']);
}


RewriteBase /folder issues on IIS for broken images

Okay, so problem is IIS does not understand our .htaccess file and has its own set of rewrite rules. If someone's facing broken images problem, best is to create an outbound rule which will add your subdirectory into the URL. something like "/sites/all/..." to be rewritten to "/drupal/sites/all/...".


Set form value to empty on validation fail

Use setValueForElement:

$new_value = '';
$form_state->setValueForElement($form['myfield'], $new_value);


What is the purpose of key_value_expire table?

Beside the form cache and the update status the key_value_expire table is mainly used by the private and shared temp store. There you find a good explanation what the purpose of this data is:

  class PrivateTempStore

  Stores and retrieves temporary data for a given owner.

  A PrivateTempStore can be used to make temporary, non-cache data
  available across requests. The data for the PrivateTempStore is stored
  in one key/value collection. PrivateTempStore data expires
  automatically after a given timeframe.

  The PrivateTempStore is different from a cache, because the data in it
  is not yet saved permanently and so it cannot be rebuilt. Typically,
  the PrivateTempStore might be used to store work in progress that is
  later saved permanently elsewhere, e.g. autosave data, multistep
  forms, or in-progress changes to complex configuration that are not
  ready to be saved.

  The PrivateTempStore differs from the SharedTempStore in that all keys
  are ensured to be unique for a particular user and users can never
  share data. If you want to be able to share data between users or use
  it for locking, use \Drupal\user\SharedTempStore.

Reference:
https://api.drupal.org/api/drupal/core%21modules%21user%21src%21SharedTempStore.php/class/SharedTempStore/8.2.x
https://api.drupal.org/api/drupal/core!modules!user!src!PrivateTempStore.php/class/PrivateTempStore/8.2.x


How to optimize already uploaded images?

The common approach is not to modify the uploaded original image, but to calculate additional image variations and serve those to your visitors. All image styles created in /admin/config/media/image-styles are automatically compressed, using the settings form /admin/config/media/image-toolkit


Is there any API to get corresponding field in a custom content type?

In this instance using db_query is appropriate...

$nids = db_query("SELECT nid FROM node WHERE title LIKE :title", array(':title' => '%'.$title.'%'))->fetchCol();

$nodes = node_load_multiple($nids);

foreach($nodes as $node) {
    $subtitle = $node->field_subtitle[LANGUAGE_NONE][0]['value'];
    // do things with the subtitle....
}

What has happened here is we are using db_query to search the node table for nodes with matching titles. Once we have the nids we call node_load_multiple and that loads the whole node(s). Drupal uses caching here so we don't have to necessarily connect to the DB at all to do this.

The resulting $node object has all of the fields already attached to it so knowing where they are actually stored in the DB at this point is irrelevant.

As Clive has pointed out we shouldn't really access field items directly as using field_get_times or EntityMetadataWrapper will ensure that we always load the field items in the correct language (the language of the current user).

To use field_get_items you could:

foreach($nodes as $node) {

    // using field_get_items here automatically loads the field in the correct language
    $field_items = field_get_items('node', $node, 'field_subtitle');
    $subtitle = $field_items[0]['safe_value'];

    // do things with the subtitle....
}


Restrict node list in entity reference field based on node field

For the PHP solution you have to provide an EntityReferenceSelection Plugin. I give you an example from my "proreos" project:

namespace Drupal\proreos\Plugin\EntityReferenceSelection;

use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection
...

/**
 * Plugin implementation of the 'selection' entity_reference.
 *
 * @EntityReferenceSelection(
    *   id = "default:proreos",
    *   label = @Translation("proreos selection"),
    *   entity_types = {"address_entity", "anwalt_entity", "library_entity"},
    *   group = "default",
    *   weight = 1
    * )
    */
class OwnEntitiesSelection extends DefaultSelection {

  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
      $query = parent::buildEntityQuery($match, $match_operator);
      ... your code here to modify the query ...
      ... (I do $query->condition('user_id', $currentUid);) ...
      return $query;
   }}

You may also need to override validateReferenceableNewEntities().
Look for more examples in the core modules.


How to set a datetime field = now() during insert?

Using a slightly different syntax (drupal_write_record):

$new_record = array(
    'field' => $form_state['values']['field'],
    'timestamp' => date("Y-m-d H:i:s", time()), //<- this
);
drupal_write_record('table_name', $new_record);


Alter render (array) of a field in a View?

I'd take a look at the views_pre_render(&$view); hook.  There, in your module, you can do stuff like:

 function MYMODULE_views_pre_render(&$view) {

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

      // do whatever you want

   }

 }

and do whatever you want meaning you have access to $view->result which is an array of all the raw data making up each row.  Throw in  a drupal_set_message('<pre>' . print_r($view->result, true) . '</pre>'); or its equivalent to take a peek at that and you should be able to work all kinds of magic.

If this doesn't work to your needs, you can still render the field any way you like from a view template for that row or field itself.


When i added the Vote results: Value type field for output. It shown like percent or points so how can we filter the varchar field type with number behavior.
I think  you should filter by Vote results: Value not Vote results: Value type


In your view's edit screen do the following:

1.) Under Format, Change Show: Content to Show: Fields

By clicking on Content and then selecting Fields

2.) Under Filter Criteria add Type and then check mark your content type name.


how to set default_value for list_boolean field equal to 1, not 0?

Actually, the behavior here is a bit weird.  The box shows up unchecked when the field examining an existing user (e.g. when browsing /user/1/edit when logged in as admin), but it does show up as checked when browsing to /user/register when not logged in.  So that was a little confusing.

Upon further investigation, the new field isn't populated at all for existing users, i.e. the database entries simply don't exist.  So those will have to be created manually it seems -- at which point I can specify whatever value I want as the "default".  In my case:

INSERT INTO field_data_MYFIELD
(entity_type, bundle, deleted, entity_id, revision_id,language,delta,MYFIELD_value)
SELECT 'user', 'user', 0, users.uid, users.uid, 'und', 0, 1 from users;


How do you add Meta-Description with Metatag?

If you want to write a manual description you should delete the whole "[node:summary]" part and put your text in its place.

The square brackets are part of the token notation and aren't needed unless you are using replacement tokens.


How to show the ip address in revision listing?

You could do this using rules and views.
First to create the rule:

  Create a text field named ip_address
  Manage display: make the field hidden
  Use Display Suite or a custom hook (or even CSS) to hide the field when filling out the form
  Create a Rule on event "Before saving content"
  Set a condition of content type: your content type
  Set a condition of Data comparison: [node:is-new], Data value: True (check the checkbox)
  Set an action of Set a data value, and set the field to be:
  PHP Code:

<?php
  print ip_address();
?>

Above taken from here: Get IP address of submitter

For your purposes the 6th bullet (your rule condition) can be set-up like this:

And for the final action (7th bullet) if you don't want to use the php you can first add and action

  'Add a variable' -> Value IP Address

and use that as in a second 'set a data value' action...

Now you can create a view that displays in a table format the fields 'Content Title' 'Revision Log' (i'm guessing this is what the operations column is recording?) and 'IP_Address', sorted by 'Node revision ID (desc)', or similar....

As it stands I am aware that this answer might not work for multiple revisions, rather only displays the IP for the latest revision. I imagine that when setting up your initial (hidden) IP_address field if you allow multiple values the rule will simply add values rather than over-write them. Maybe someone else on here has guidance on that...


Listing content inside an OG based on a tag name provided in the URL

Ok, answer to my question is that when the filter is not available, I should provide a default value -> raw value from URL -> path component = 2

And check "use path alias" option to avoid using regular paths.

And also argument input = from panel argument (first).


Programmatically get the date field value

Try this out -

$schedule_start = $form_state->getValue('field_start')->format("Y-m-d H:i:s");
$schedule_end = $form_state->getValue('field_end')->format("Y-m-d H:i:s");

Provide your own desirable format.


Print module download pdf file name change characters into HTML entities

I am not a specialist of dompdf, but having used fpdf, I think it's something you do in your print template or custom module that converts the fields in dompdf format.
You may need to set a php rule like this:

$title = mb_convert_encoding($title, 'HTML-ENTITIES', 'UTF-8');

Source: https://stackoverflow.com/questions/16384517/dompdf-character-encoding-utf-8

Or another one like this:

$titlePrintFriendly = preg_replace('#&amp;#',chr(38),$title);

and then print $titlePrintFriendly

I used the second one in the past to trick printing some special chars.
The dompdf library should be loaded in the file you add this line.

I took the char number from https://github.com/dompdf/dompdf/blob/master/lib/fonts/Symbol.afm


you need to edit /drupal/sites/all/themes/MYTHEMENAME/template.php
then add the following code.
function MYTHEMENAME_preprocess_views_view_fields($vars){
      if ($vars['view']->name == "VIEWNAME" && $vars['view']->current_display == "DISPLAY" && $vars['id'] != 1){
        $vars['fields']['title']->content = '';
      }
    }

What this code is saying is if your row is not equal to (!=) 1, then don't display anything. Thus, it will print your title only for row 1.

replace MYTHEMENAME with your actual theme name.

replace VIEWNAME with your view's name. example: flagged_content

replace DISPLAY with your view's machine name. You can find this by editing your view, then under Advanced -> other
examples: block, block_1, page, page_1 or default. It's default if you're using your master view.

For user's separated by comma you would have to use css for that.
JS FIDDLE EXAMPLE
PS: I think you would have to change it from grid to html list for your view.


How to modify a core theme and what is the correct way to do this?

What you want to do is create a subtheme of Bartik, and make your modifications to node.tpl.php there instead. Themes support the notion of inheritance, so this can be leveraged to tweak core themes without actually hacking core. As a rule, it is best practice not to hack core for the reasons you mentioned and a slew of others, security not the least among them.


setting the url to a function in a custom module

The page callback must be the name of the function that will return the data from database

You must create a function like this :

function my_callback(){
// here you will connect and pull up data from the database
return $your_data;
}

Also don't forget to clear the cache and read about the database API here


Getting a list of nodes of a certain type sorted by number of votes

You can use views module to list nodes sorted by votes..

You can see the query executed in views when you enable Show SQL Query in views settings (admin/structure/views/settings) in the view preview...


With states, how to uncheck a disabled checkbox, but not check it when it becames enabled?

Turns out that with current implementation of states it is not possible. When condition gets true, state is applied, and when it gets false, state gets removed. No way around it so far, not without hacking core, so it's more feasible to write custom behaviors instead.


Add a class to the first li.pager-item for a view pager?

If you implement theme_pager you'll be expected to create the entire pager render array from scratch using several theme function - theme_pager_first, theme_pager_previous, theme_pager_next and theme_pager_last. That seems like entirely too much work for adding one class.

Since theme_pager calls theme_item_list at the very end to build the final render array, you can use hook_preprocess_HOOK to modify the pager render array before drupal renders it into HTML.

function THEME_preprocess_item_list(&$vars) {
  // make sure we're dealing with a pager item list
  if (isset($vars['attributes']['class']) && in_array('pager', $vars['attributes']['class'])) {
    // make sure there are items
    if (count($vars['items'])) {
      $vars['items'][0]['class'][] = 'test';
    }
  }
}

Clear the cache after adding this hook.

UPDATE: find the first li.pager-item:

function THEME_preprocess_item_list(&$vars) {
  // make sure we're dealing with a pager item list
  if (isset($vars['attributes']['class']) && in_array('pager', $vars['attributes']['class'])) {
    // loop the items and find the first .pager-item
    foreach ($vars['items'] as $index => $item) {
      if (in_array('pager-item', $item['class'])) {
        $vars['items'][$index]['class'][] = 'test';
        break;
      }
    }
  }
}

UPDATE2: find first and last li.pager-item:

function THEME_preprocess_item_list(&$vars) {
  // make sure we're dealing with a pager item list
  if (isset($vars['attributes']['class']) && in_array('pager', $vars['attributes']['class'])) {

    // loop the items and find the first and last .pager-item
    $first = FALSE;
    $last = NULL;
    foreach ($vars['items'] as $index => $item) {
      if (in_array('pager-item', $item['class'])) {

        // first
        if (!$first) {
          $vars['items'][$index]['class'][] = 'test';
          $first = TRUE;
        }

        // last
        $last = $index;
      }
    }

    if (!empty($last)) {
      $vars['items'][$last]['class'][] = 'test2';
    }
  }
}


Some corrections after, can you put the context of the execution? Like the function where you call this code and where you output $file variable?

$wrapper = entity_metadata_wrapper('node',$variables['node']);
// raw() should give you file object in your case
$file_field= $wrapper->field_library_file->raw();
// theme_file_link 'file' parameters have to be a file object
$variables['file'] = theme('file_link', array('file' => $file_field ));

Docs :

theme('file_link') OR theme_file_link
Raw() Method

Note :

@clive comment : no need to value() because he have already used that function below, if we follow the source code given... In that case, value() and raw() methods should return the same file object.

theme('file_link', array('file' => $file_field))

Edit : Can you dump your $file_field variable? You can do it via this snippet

drupal_set_message('<pre>'.print_r($file_field, true).'</pre>');


How to acces gmap markers after map is generated?

Here is a quote from the Comparison of mapping modules:

GMap is considered a legacy module.

So maybe you want to have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.


Drupal 7 Views filter criteria Entity Reference

Correct me if Im wrong but I think the problem is that Type Reference filed is actually node id.

What worked for me is the following:

Add a relationship from the Type Reference field.
Add the field you are trying to use as filter and use relationship from (1). Set your operator and value.
Profit!

P.S. It seems that using Taxonomy terms would be a better solution though i have no idea what you are trying to achive.


Custom PHP vs Drupal Workflow for a Web Application not Websites

Your questions are somewhat vague but I'll provide some examples:

For instance I have a site that from a CSV file allows certain visitors emailed access keys to access a Webform and its tracked via a custom Node that has an embedded field collection and this relationship + status is tracked via a Relation. I use the Migrate module to add or update allowed visitor information from the CSV.

I use the Webform API, EntityFieldQuery's and drupal hooks to do my webapp business logic. Drupal core and contrib modules provide additional APIs. I use Views Send for bulk emailing.

I have another form site for class reviews for a campus. I use Migrate to pull $form structure info from a 3rd party survey database and then use a custom drupal entity and the drupal Form API to build a custom form from remote data. The remote database has a custom schema for say: Question, Options, Question position in Form, Form ID, etc ... it gets converted into a drupal $form array with some simple PHP in a Migration class. Again I use Relation to track what the student has completed between a uid and a nid. I use the drupal authorization mechanisms such as authmaps to integrate our local LDAP server.
On another site students should fill out like 10 content types after login. I use hook_menu_alter and a cookie to assure a student has Opted-In daily to EULA's for uploaded content. Then I use the core Form API to link 10 node edit forms on submission from 1 to another. Creating a kind of workflow for the student.

There are numerous times where knowing the Drupal contributed modules that help you create business logic, such as: Rules, Triggers, Rules Link, Maestro and WorkBench all help you create types of business logic.

Modules like References, Relation, Field Collection, Paragraphs let you create "embedded relationships". Mix and match as you need.

... I got tired of linking contrib modules :P


Using Invisimail within a Contemplate Template

I'm doing a similar thing, but in a node template. To get the javascript obscured code to return, use the js_entities encoder similar to this:

<?php
$email = render($content['field_email_address']);

// this takes the email address and turns it into a "mailto:" link, otherwise use 'link' => 0
$email_settings = array('link' => 1);

echo "<p>" . invisimail_encoder_js_entities_encode($email, $email_settings) . "</p>";
?>

Also, I use the Quick Javascript Switcher extension in Chrome to quickly toggle js off/on to see if things like this are working:

https://chrome.google.com/webstore/detail/quick-javascript-switcher/geddoclleiomckbhadiaipdggiiccfje


View: taxonomy_term, additional display of type page

You can only have one page display on a particular path.

If you want to display two views on one url there are a number of ways you can do it.

Have one display page as you have, then have the second view as an attached view.

Or

Display the second view as a block and use context to display it on the same url


Views allows you to set the acess within the UI, you can restrict based on roles or permission.

Usually that should be enought but if you need to set a custom access callback you can use hook_menu_alter but you will also need to make sure your module is called after the views hook_menu_alter, you can change the weight of your module in the database or you can use hook_module_implements_alter to make sure your module is called after the views module for the menu alter hook.


Twitter Card Preview is failing with twitter:image

I made a test with this values

<meta name="twitter:url" content="http://liberalgeek.com/content/why-do-atheists-celebrate-christmas" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:creator" content="@kennywyland" />
<meta property="twitter:description" content="I can&#039;t speak for all atheists, I can only speak for myself, so please leave a comment below and explain why you celebrate Christmas! When I hear someone ask, &quot;Why do atheists celebrate Christmas?&quot; my first thought often is: Better Question: Why do Christians celebrate Christmas?" />

<meta name="twitter:title" content="Why do Atheists celebrate Christmas?" />

<!-- the following line causes the problem -->
<meta name="twitter:image" content="http://graphics8.nytimes.com/images/2012/02/19/us/19whitney-span/19whitney-span-articleLarge.jpg">

Changing the image, the card works normally in the preview tool.
I would try to check if you have some restriction on the file.
Have a look at the crawling section of the API docs

  Twitter's crawler will respect robots.txt when scanning URLs. If a
  page with card markup is blocked, no card will be shown. If an image
  URL is blocked, no thumbnail or photo will be shown.

UPDATE
As suggested by the author of the question, changing robot.txt could not be enough. Since Twitter could have cached your file, you need to wait at least 24 hours to let it expires.
I add that the same problem could be found not just on robot.txt file, but also on images. Indeed, wrong Twitter cache could lead to a 404 error and a broken preview image.


One possibility is to use the Views Field View module:

  This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.

Also, there is the 'Rewrite results' options in Views definition.

Alternatively by code, you can use use a field--[type|name[--content-type]|content-type].tpl.php file to override the rendering of the field. You would then have to access the $element['#object'] to get access to the other field that you would need to render manually. Reference: https://api.drupal.org/api/drupal/modules%21field%21theme%21field.tpl.php/7


How replace a node term programmatically?

you can add term using term id(tid) $node->field_yourfield_name[$node->language][0]['tid'] = $tid in D7


If I understand correctly, it is okay for the block to be cached, but each path/URL can have its own "version" of the form, right? In that case, you need to inform Drupal that this block changes depending on the current path/URL. Drupal 8 introduced the concept of "cache contexts" to do that. The cache context defines the external factors by which the return value can vary.

Now that you know this, you'll notice that this question is pretty similar to yours.

As documented in the change record, blocks can define their cache context by overriding the getCacheContexts() method from the BlockCase class. Overriding that method would probably look like this in your block class:

/**
 * {@inheritdoc}
 */
public function getCacheContexts() {
  return Cache::mergeContexts(parent::getCacheContexts(), ['url.path']);
}

As you  can see I'm using the url.path context here. A list of contexts provided by Drupal core can be found in the documentation.


Bulk deletion of node which are unpublished and which are in between the given dates

I suggest to use the Rules module for that.
Bulk deletion is explained in one of the first tutorial video's in this series:
https://drupalize.me/videos/introduction-rules?p=1157

What you should do:

enable Rules and Rules UI
create a new Component of type "action set"
actions to add: a loop thru the nodes and if the date matches, the node should be deleted

The Views Rules module might be usefull to use views to send the nid's of the nodes to delete to the rules component.
I learned a lot about this via the accepted answer to "How to pass arguments to a view from Rules?".

An alternative could be the Views bulk operations (VBO) module, which has a "bulk deletion" out of the box. You add a VBO-field in your view and select the "delete" as the action. Maybe this is even better than the Rules (in the way that it will take less time to understand and implement).


A query like that should do the trick, but if you want something more elegant, I recommend EntityFieldQuery.


Geolocation Field Oops! Something went wrong

Usually you see this message when you don't have in the Geolocation module the Google API Key or the Google API Key is not working well. For this you need to go to:

http://YOURSITE/admin/config/content/geofield_gmap

Write your working Google API Key and save the Configuration.

Edit:

To apply the patch you need download the file to:

sites/all/modules/geofield/modules/geofield_map

then go to the dir and run:

patch -p1 < fix-api-key-not-being-used-2746209-5.patch


How do I show a coupon code to customers?

The UC coupon module doesn't have a general purpose coupon retrieval function.

If you're solely looking to retrieve an active coupon, you can follow what the module itself does: query the DB table uc_coupons for rows with column status = 1. Using a DB query will let you modify it to whatever your particular case (e.g. 1 or more results, bulk codes, date range, etc.).


Commerce: adding +/- buttons to the Quantity field

Commerce Kickstart has that.

We use the jquery_ui_spinner library, extracted in our libraries folder.

We declare the library in a hook_library implementation:

/**
 * Implements hook_library().
 */
function commerce_kickstart_product_ui_library() {
  $libraries['jquery_ui_spinner'] = array(
    'title' => 'jQuery Spinner',
    'website' => 'http://github.com/btburnett3/jquery.ui.spinner/',
    'version' => '1.8',
    'js' => array(
      libraries_get_path('jquery_ui_spinner') . '/ui.spinner.min.js' => array(),
    ),
    'css' => array(
      libraries_get_path('jquery_ui_spinner') . '/ui.spinner.css' => array(),
    ),
    'dependencies' => array(
      array('system', 'ui.widget'),
    ),
  );
  return $libraries;
}

Then in our hook form alter we attach the library:

function commerce_kickstart_product_ui_form_alter(&$form, &$form_state, $form_id) {
  if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {
    $form['#attached']['library'][] = array('commerce_kickstart_product_ui', 'jquery_ui_spinner');
  }
}

and finally in our JS file we do:

(function ($) {

  // Add a spinner on quantity widget.
  Drupal.behaviors.quantityWidgetSpinner = {
    attach: function ( context, settings ) {
      $('.form-item-quantity input').spinner({
        min: 1,
        max: 9999,
        increment: 'fast'
      });
    }
  }
})(jQuery);


Problem with field storage for custom content type modules

The Drupal's config management system which are you using to install configuration isn't really built for this. There are several ways to go about this. The main issue is that the config management system automatically create dependencies and such for you, which is a bit troublesome to manage.

Drupal doesn't have a concept of a shared field, it simple has a field store and field instance, but this isn't owned by a module.

So for solutions, there are some ways to go about this.

Let one module own the field storages you want to want to share and let modules that share fields depend on the module. Note the field can be deleted eventhough it's in a modules install folder, as it's just configuration, unless you lock it. A variation of this would be to combine the modules, into a single module, so all config is install at the same time.
Don't use shared fields - if the modules are independent, it makes sense that they shouldn't share configuration.
Use code to install fields. This is similar to how you define fields for entities, only you need to use FieldConfig and FieldStorageConfig. Drupal have many test cases that does this, which you can use as a guide. Some example code looks like this:

$this->fieldStorage = FieldStorageConfig::loadByName('entity_test', $field_name);
if (!$this->fieldStorage) {
  $this->fieldStorage = FieldStorageConfig::create(array(
    'field_name' => $field_name,
    'entity_type' => 'entity_test',
    'type' => 'link',
  ));
  $this->fieldStorage->save();
}

$this->field = FieldConfig::create([
  'field_storage' => $this->fieldStorage,
  'bundle' => 'entity_test',
  'settings' => array(
    'title' => DRUPAL_DISABLED,
    'link_type' => LinkItemInterface::LINK_GENERIC,
  ),
]);
$this->field->save();


Show facebook friends activities from my site

I used Drupal for Facebook module, it provides a views filter 'Friend of current user'.
 For showing various activities, 'Activity' module used. Then with help of view the friends activities filtered.


How to show the tabs according to the logged in user role? (Omega subtheme)

If you are using the Omega sub theme then there would be a template file for each of the regions defined by the Theme.

The content comes in the template called region--content.tpl.php

You should see the tab printed there. you can put your logic there.


Enable the 'Complete entity view' filter and then select the field 'Entity HTML output'. This will put the entire page in one field including any beans on that page.

I assume there is a better solution but I have not found one yet.


What do I put in the drupal 7 commerce Checkout Completed Rules: Send Email field to display all of the order data?

I think this is a permissions issue related to line items and anonymous users. See https://drupal.org/node/1811972, and https://drupal.org/node/1333174.

This does not answer your exact question, but what I've done recently is install Commerce Invoice Receipt (https://drupal.org/project/commerce_invoice_receipt) as a solution. Here's the basic checklist I followed:

install commerce invoice receipt (dev version has support for logo)
set visibility of fields at admin/commerce/config/order/display/invoice
disable SQL query rewriting on on Line items view - needed for line
items to appear when emailed to customer (security issue, but I'm not sure how serious)
create a new rule with Send Invoice Receipt action - for customers
create a new rule with Send Invoice Receipt action - for admins
disable rule: Send an order notification e-mail


Content Type - Image able to link to other website

you can do this by using any of the below modules :

Image Link Formatter

  This module is the result of the discussions around a requested feature
  to allow an image field to be displayed with a link to a custom URL

Image URL Formatter

  This module add a url formatter for image field. Then you can output
  image url directly.

  Most of the code, maybe more than 90%, is just copy from the drupal
  core. I think it is stable enough.

  I have created a content type, and add an image field instance to it,
  later i use views to export the data of this content type.And i want
  to output the data,then i could import it into another drupal 7 site
  with feeds module. What i need is the url of the image field, but i
  could not export the image url directly. That is why i create this
  small module.

Link

  The link module can be count to the top 50 modules in Drupal
  installations and provides a standard custom content field for links.
  With this module links can be added easily to any content types and
  profiles and include advanced validating and different ways of storing
  internal or external links and URLs. It also supports additional link
  text title, site wide tokens for titles and title attributes, target
  attributes, css class attribution, static repeating values, input
  conversion, and many more.


Using different .inc files with same function names in .module file

You can use file key in your menu like:

I assume you have a includes directory contain both files my_project_mobile_api.v1.inc and my_project_mobile_api.v2.inc and both files contain account_register function.

Your hook_menu should be like the following.

function my_project_mobile_api_menu() {
  return [
    'api/v1/user/register' => [
      'page callback'   => 'account_register',
      'access callback' => 'user_is_logged_in',
      'type'            => MENU_CALLBACK,
      'file'            => 'includes/my_project_mobile_api.v1.inc',
    ],
    'api/v2/user/register' => [
      'page callback'   => 'account_register',
      'access callback' => 'user_is_logged_in',
      'type'            => MENU_CALLBACK,
      'file'            => 'includes/my_project_mobile_api.v2.inc',
    ],
  ];
}

You can also use 'file path' if you files not in the same module take a look at this example.


Creating search pages for specific content types

The best method for me is Search API:

  This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine.

Uses multiple backends (solr, database, elastic search), is fully integrated with views, etc.


Rules to remove user from role on node publish

I solved this with the rule on updating node and by setting the following  conditions:

that the current-user is not an admin nor the node author
that updated node status is published
that the corresponding form field is not empty

THen the action is set to remove user role of current-user from [desire_role]


This will work for you:

$node = new stdClass();
$node->title = "My title";
$node->type = "mycontent";
node_object_prepare($node);
$node->uid = $user->uid;
$node->status = 1;
$node = node_submit($node);
node_save($node);

More details you can see at
https://www.drupal.org/docs/7/howtos/create-a-node-in-code


Should I create a new Form or use form alter?

The distinction is simple:

If you need to add some fields to an existing form, and keep all of it's original functionality (or at least most of it), use hook_form_alter.
If you need to create a totally new experience, put it under different path and create form from scratch, like shown in Examples for developers
If you feel you need totally new form under already occupied path, think again as it might cripple existing functionality.Feel free to ask more specific question then.

Then, if you want a form at 2 pages, you have 2 choices:

If form will be the only significant element on these pages, make it a page (or pages) with hook_menu
If there are supposed to be other forms, submitted independently, wrap it into a block.


How to migrate multi role to an user using migrate csv plugin

First put your all roles inside double quote separating by comma (,) and be sure that your all roles on csv file must be role's machine name.

then edit your config file something like this....

process:
  name: name
  mail: email
  pass: password
  roles:
    plugin: explode
    delimiter: ','
    source: roles
  status: status
destination:
  plugin: 'entity:user'
  md5_passwords: true

you have to use plugin: explode provided by drupal to import multiple roles separated by comma (,).

And if you are importing password also then use md5_passwords: true


Show access denied in custom page without permissions

As a replacement for drupal_access_denied() this in Drupal 8 you can use :

if(empty($userId)){

throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();

}

This shows the access denied page in the browser.


Best practice depends on where the code is placed.

OOP Code

Use $this->t().

If you extend a drupal base class like a controller or a plugin the t() function is provided as class method $this->t() out of the box and you should use it. This makes your code testable.

For most tasks you'll find a suitable drupal class to extend from which has $this->t() defined, but if you need to build your own class from scratch best practice would be to use the string translation trait and inject this as service if you use this class in a service context:

use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
class MyClass {
  use StringTranslationTrait;

  /**
   * Constructs a MyClass object.
   *
   * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
   *   The string translation service.
   */
  public function __construct(TranslationInterface $string_translation) {
    // You can skip injecting this service, the trait will fall back to \Drupal::translation()
    // but it is recommended to do so, for easier testability,
    $this->stringTranslation = $string_translation;
  }

  /**
   * Does something.
   */
  public function doSth() {
    // ...
    $string = $this->t('Something');
    // ...
  }

}

Source: https://www.drupal.org/docs/8/api/translation-api-code-text

Procedural Code

Use t().

If you have procedural code, for example a hook, then use t(), which is a global function.

Not best practice would be to use the procedural t() in OOP Code.


How to solve “Query failed” error in drush sql-sync output 2?

At the time of writing this comment, there is a problem in drush 9 with php7.4 as mentioned here: https://github.com/drush-ops/drush/issues/4319#issuecomment-649223069
I solved it in my case (I have multiple PHP versions installed) by switching to php7.2 using this command:
sudo update-alternatives --set php /usr/bin/php7.2
I think it will work also with php7.0 and php7.1


Probably best to add your own Quicktabs style and use CSS background images.

In a custom module

function MYMODULE_quicktabs_tabstyles() {
  $tabstyles_directory = drupal_get_path('theme', 'MYTHEME') . '/quicktabs';
  $files = file_scan_directory($tabstyles_directory, '/\.css$/');
  $tabstyles = array();
  foreach ($files as $file) {
    // Skip RTL files.
    if (!strpos($file->name, '-rtl')) {
      $tabstyles[$file->uri] = drupal_ucfirst($file->name);
    }
  }
  return $tabstyles;
}

CSS files in THEMEDIR/quicktabs/*.css will be read as a potential style

In your theme dir, add /quicktabs/image-tabs.css

Clear all caches

New style should be available, with accompanying CSS classes, add to your new CSS file.

Alternatively target the existing quicktabs classes with CSS.

Basic CSS background image tute here


Those blocks can be referenced and arrangaed inside the page by using
  an entity reference field.

These "block contents" should be a different content type, since you are not using (based on your writing) the block functionality at all. After that, you can define your own display for this content type, and also create a twig template for it.


7 Views $variables/$views/$fields crashing browser

Instead of using kpr or devel or the like, switch to using a debugger like xdebug. Sometimes these arrays are so large that simply rendering them in the browser can crash it. This happened to me all the time with Drupal 8 and kint.


After changing a webform multi-select field to single-select, submissions made pre-change show only the first selection

You can keep the field set to single choice, and use hook_webform_submission_render_alter() to display the values as if it was still a multi-select field.

You can use the hook in a module or the template.php of a theme. If you are thinking about implementing it in a theme, keep in mind that the Webform Results view is displayed through the Administration theme. So, the hook must be implemented in the default administration theme for it to work in that view. By implementing it in a module, you shouldn't have to worry about which theme the submission results are being shown.

You will need the nid for the webform, and the form Key for the select field. The nid is in the url of the webform's edit page. The form key can be seen in the webform's Form componentspage.

The following code is implemented in the "my_module" module, for a webform with a nid of "100", and a field with the form key "my_select_field".

/**
 * Implements hook_webform_submission_render_alter().
 */
function my_module_webform_submission_render_alter(&$renderable) {
  if ($renderable['#node']->nid == '100' && isset($renderable['my_select_field'])) {
    $renderable['my_select_field']['#multiple'] = 1;
  }
}

The isset($renderable['my_select_field']) in the if statement may seem redundant, but it's there to prevent an exception if someone changes the form key for the field.


A entity is data structure defined by hook_entity_info() and can be fieldable, which means that you can add fields to them.

In Drupal 7 Core, Nodes, Users, Comments, Vocabularies and Terms are entities.

In Contrib, there are many more, for example private messages and commerce as like a dozen of them ;)

However, I think job postings are perfectly fine as nodes :) Entities don't automatically have Pathauto (Tokens), Views etc. integration.


"Rendered" View style for a Taxonomy Term?

At "Format > Show" there is an option "Rendered entity".

Apply it and then you can choose term's "View mode" in the select dropdown.

Also you can install Display Suite and notice new option "Display suite" at "Format > Show".


Drupal front page blog entries custom sort order

You may add your custom field "sort_order" to the blog content type, then create a page view (/admin/structure/views/add) for the blog content (just like node does it in the "frontpage" view - you may even copy that view and restrict the nodetype to blog in your copy).

Then change the "sort criteria" in the view to your sort_order custom field.

Then you're done.


How does one diplay only the referenced entities associated with specific node in a view block?

If you use Drupal 7, you must go to: Structure > Views > (Choose the view you want to customize).
There you will find a section "Filter Criteria" if nothing exists press add on the right and add your criteria. You select it and continue with the customization, each element has different customization.

On the bottom you usually see the result, if nothing is shown, then this does not necessarily mean that you made a mistake (I had that problem once). Don't forget to save.


The process is rather different. There are some common elements but maybe what can get confusing is how D8 leverages the Symfony Framework.

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();

$kernel->terminate($request, $response);

As can be witnessed by the index.php, things look a bit different. But it is essentially "bootstrapping" functionality. To get a really good sense of what is going on, I would highly recommend reading the following:

https://cipix.nl/understanding-drupal-8-part-1-general-structure-framework

Also, the Drupal 8 Documentation helps to get a good grasp on what is available to work with:

https://www.drupal.org/docs/8/

Especially giving the API's a good looksy:

https://www.drupal.org/docs/8/api

As I said, it's quite different than before. A lot more OOP going on. It's quite powerful and gives developers a lot more tools to work with but if you aren't used to how PSR-0 and PSR-4 autoloading work, you might find it hard to debug and grock.

Good luck and Happy Drupalling!


How to make the commerce_kickstart distribution fully multilingual?

You'll want to look at these two different resources:

Configure entity translation for Drupal Commerce

and

Search API Entity Translation


Drupal multi site 404s, sub directory site subpages going to default site

You didn't mention anything about sites.php, so I'm going to guess that's where the problem resides.

Google it: https://www.google.com/#q=drupal+multisite+sites.php
D7 example: https://api.drupal.org/api/drupal/sites!example.sites.php/7.x
D8 example: https://api.drupal.org/api/drupal/sites!example.sites.php/8.2.x

Please post your sites.php file if you're unable to fix the issue after taking a look.


What's a good balance between reusing fields versus creating new ones in the context of fields scalability?

The amount of data in a field usually isn't a problem. If you're worried about that, look into alternative field storage plugins or write your own. For example MongoDB, which can deal with pretty much anything you put into it. It is for example used on http://examiner.com.

A real problem however is the number of fields you have. Because currently in Drupal 7, the complete field configuration of all fields, no matter if they're loaded or not, is fetched from the cache on every single request.

I've seen sites with 250+ fields, where loading and unserializing the field configuration takes 13MB+ memory.

Edit: The field info cache has been improved (see http://drupal.org/node/1040790 for details) with Drupal 7.22, only the fields of bundles that are displayed on a certain page are loaded from the cache and they're separate cache entries. That only works if there are no wrong API calls that request instances across multiple bundles.


How to theme views using Taxonomy Terms?

Are you saying that you are using the not-yet-stable 7.x module Taxonomy Theme? Terms are assigned by Term Reference fields on fieldable entities.  Since drupal is open source, there is always more than one way to do something.  If you wanted to build a site that can do exactly as you have asked here, then I suppose it is possible to make a new entity that has a term reference and also embeds the view in its custom theme processes to get the fusion you are requesting.  You will have to crawl into the Taxonomy Theme module code and see if it is using hook_node_view to do the check/change.  If so, it would not fire on a straight view anyway but this custom entity (maintenance nightmare) should trigger it.

An easier method would be the template files that you dont want.  Use theme_hook_suggestions where you have different tpl.php files for the different views based on path or whatever else you want.  Different templates by path alias.  You then just have the different templates use the different theme styles.  I would also recommend putting the taxonomy term values as body level css classes so you can have one theme, and it just trigger different stylesheets based on term classes. Option1 | Option2  This would relieve your dependence on the dev-version module.

Option 3.  In whatever theme is your default, copy the relative style sheets over from the other themes and just use the view-specific css class for each one, applying it manually.  This means that you have duplicated style commands, so it will be a little harder to maintain what is coming from where, but at least you dont have to code any php.

Option 4.  Sareed's comment about using block displays and embedding the views on other pages that have the terms.  (...I should have thought of that)


You forgot to add the language to your fields:

$node->field_profile_fn[LANGUAGE_NONE][0]['value'] = $fbuser->first_name;

But even then, this is not the way to go. You should take a look at https://www.drupal.org/documentation/entity-metadata-wrappers

This approach allows you to use something like this:

 $wrapper->field_profile_fn->set($fbuser->first_name);
 $wrapper->save();


How to match a Drupal path in Apache config

The directive I was trying to insert was Require all granted.  I managed to achieve the same effect by proxy-passing requests for /foo/bar to another virtual host running on the same machine, but unreachable from outside.  That 2nd virtual host did not require auth, which achieved the same effect as Require all granted.

ProxyPass /foo/bar http://example.local/foo/bar
ProxyPassReverse /foo/bar http://example.local/foo/bar


How to create multi select within select box in views expose filter in Drupal?

User Better Exposed Filter, this module will give exact thing.

ok then in  Exposed form style -> BEF Settings ->


Multiple choice question creation change checkbox to radio

If I'm not mistaken, as long as you don't check the "Multiple Answers" option in the answer settings tab, your answers for that question will render with radio buttons on the front-end. This doesn't change the checkboxes to radio buttons when you are editing a question, but that's because you are supposed to be able to mark multiple correct answers for each question, if need be.


How to download and enable module needing to subscribe to rss?

In the right side menu there will a link Browse code repository. There you can find git clone URL

git://git.drupal.org/project/node_redirect.git

So you can clone it.


What do I have to do to get the Modernizr module to work in Drupal?

Modernizer detects feature support in browsers and adds css classes to the HTML element based on those features.  You use those css classes to target newer features to browsers that support them.  While it will add HTML5 support to older browsers via the HTML5Shiv, it will not add CSS3 support.

To add support for CSS3 features in older browsers, you'll need to add a polyfill  Modernizer has a method called Modernizr.load() that lets you load the polyfill only when you need it.


Webform/YAML Form component email mapping

The feature has been added to the latest dev release of Webform-8.x-5.x.

@see Issue #2854021 by jrockowitz: Send email based on element options selection


I think you're on the right track with adding a second custom field to allow the user to choose the glyph.

Once the user has set the title, selected the glyph and saved,  you can merge the two using a template file.

https://api.drupal.org/api/drupal/modules!field!theme!field.tpl.php/7

The one you'd want I think would be named something like this:  field--title--basic-page.tpl.php

In there, you can stick the value of the glyph next to the title.  Does that make sense?


Try this variation of your rule (using the rules UI to import it in your site):

{ "rules_entityform_client_confirmation_email_pv" : {
"LABEL" : "Entityform Client Confirmation Email PV",
"PLUGIN" : "rule",
"OWNER" : "rules",
"TAGS" : [ "entity_rules_entityform_submission" ],
"REQUIRES" : [ "rules", "mimemail" ],
"USES VARIABLES" : {
  "entity" : { "label" : "Entity", "type" : "entityform" },
  "continue" : { "label" : "Continue Rules", "type" : "boolean" }
},
"IF" : [
  { "user_has_role" : { "account" : [ "entity:user" ], "roles" : { "value" : { "4" : "4" } } } }
],
"DO" : [
  { "drupal_message" : { "message" : "Email to: [entity:user:mail]\r\nHi [entity:user],\r\nThanks for creating a new project\r\n" } },
  { "mimemail" : {
      "USING" : {
        "key" : [ "entity:entityform-id" ],
        "to" : [ "entity:user:mail" ],
        "from_name" : "[site:name]",
        "from_mail" : "somebody@example.com",
        "subject" : "New Project Created",
        "body" : "Hi [entity:user],\r\nThanks for creating a new project",
        "plaintext" : "Hi [entity:user],\r\nThanks for creating a new project",
        "language" : [ "" ]
      },
      "PROVIDE" : { "send_status" : { "send_status" : "Send status" } }
    }
  }
],
"PROVIDES VARIABLES" : [ "continue" ]
}
}

The only difference with your exported rule is the line with from_mail that is added (and a slightly different machine name of your rule). Adapt the eMail Id I used to fit your needs.


Will manually setting the expire timestamp in the boost_cache table actually expire the cache for a node?

You might prefer to use

boost_expire_node

which will actively flush the node from boost static html cache

It could be scheduled, if needed ( e.g a hook_cron_queue_info implementation worker callback ) or done as an immediate expiry


Restrict user profiles access with hook_menu_alter

All the pieces of the original user menu items are defined in modules/user/user.module via the User Module's hook_menu().  The key ones here are (IMHO) user/%user for viewing the user page, and user/%user/edit for editing it, eg pages like user/1 to look at uid 1's user page, and user/1/edit to edit that same page.

So, from a logic standpoint, I am going to assume you want this:

  If a user wants to look at or edit his or her own page, allow them to
  do so.  Furthermore, if another user has appropriate permissions,
  allow them to look at and/or edit these pages as well. But no one else
  should be able to look at any other user's pages (let alone edit
  them).

Ok, so how can we do this.  Let's first look at the original view the user page menu item:

$items['user/%user'] = array(
  'title' => 'My account',
  'title callback' => 'user_page_title',
  'title arguments' => array(1),
  'page callback' => 'user_view_page',
  'page arguments' => array(1),
  'access callback' => 'user_view_access',
  'access arguments' => array(1),
  // By assigning a different menu name, this item (and all registered child
  // paths) are no longer considered as children of 'user'. When accessing the
  // user account pages, the preferred menu link that is used to build the
  // active trail (breadcrumb) will be found in this menu (unless there is
  // more specific link), so the link to 'user' will not be in the breadcrumb.
  'menu_name' => 'navigation',
);

Here we would want to change the 'access callback' to include further logic, so the menu alter would only have to change that, nothing else, eg, something along the lines of this:

function YOURMODULE_menu_alter(&$items) {

  $items['user/%user']['access callback']='YOURMODULE_user_access';

}

and then you could write something like this:

function YOURMODULE_user_access($account) {

  if ($account->uid) { // so we don't try to look at an anonymous user

    $account = user_load($account->uid); // load the full user object (ADDITION:  was user_load($uid) in original post, oops)

    if ($GLOBALS['user']->uid == 1) { // admin super user
      return TRUE;
    }

    if ($GLOBALS['user']->uid == $account->uid) {
      return TRUE; // same user so allow (we will assume blocked users aren't logged in)
    }

    if ( /* whatever logic you need to allow coordinators to access the user is TRUE */ ) {
      return TRUE; // or return $account->status; if you want to take blocked accounts into effect
    }

  }

  return FALSE;

}

So, barring any brain freezes or typos on my part, the above should work for viewing, but I did just type it in freehand, so buyer beware.  But, now, let's look at the original user edit menu item:

$items['user/%user/edit'] = array(
  'title' => 'Edit',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('user_profile_form', 1),
  'access callback' => 'user_edit_access',
  'access arguments' => array(1),
  'type' => MENU_LOCAL_TASK,
  'file' => 'user.pages.inc',
);

And once again, all you want or need to do is change the 'access callback', eg, your hook_menu_alter() is now...

function YOURMODULE_menu_alter(&$items) {

  $items['user/%user']['access callback']='YOURMODULE_user_access';
  $items['user/%user/edit']['access callback']='YOURMODULE_user_access';

}

and yes, since the logic is the same, you can use the same function all over again.

Caveats:  We are totally ignoring Drupal's built in permissions, eg, user_access('access user profiles') and user_access('administer users') in the above.

Also, if you find after doing this you can't load user.pages.inc, Drupal is most probably looking for it in your module's directory instead of the user module's where it sits, so set 'file' => drupal_get_path('module', 'user') . '/user.pages.inc' and you should be set.

Anyways hope this stream of consciousness helps out!


You can edit or create a "maintenance-page.tpl.php" file in your theme directory and edit that to theme your maintenance page.

You can view the source on the Drupal API page


How to add new form field dynamically on selected change using ajax

Build form elements in buildForm() only, not in ajax callback. The ajax callback is only for preparing the ajax response. When the ajax callback is called, buildForm() has already run with the updated $form.

Your ajax response is empty. You didn't add any ajax command to it. See ajax examples how you can do this.

But in your case you don't need any code in ajax callback. It would be enough to simply return the changed part of $form in a div container.

For this put an empty container in buildForm() and move the select form element from the ajax callback to buildForm() and put it in the container, if the condition in $form_state is met:

$form['ajax_wrapper'] = [
  '#type' => 'container',
  '#attributes' => ['id' => 'ajax-wrapper'],
];

if ($form_state->getValue('level1') != false) {
        $form['ajax_wrapper']['level2'] = array(
            '#type' => 'select',
            '#description' => 'Please select level two term',
            //'#options' => $terms,
            '#attributes' => array(
                'class' => array(
                    'mycategory'
                ),
            ),
        );

And the ajax callback:

public function ajaxCallback(array &$form, FormStateInterface $form_state) {
  return $form['ajax_wrapper'];

change #ajax to:

'#ajax' => [
  'callback' => '::ajaxCallback',
  'wrapper' => 'ajax-wrapper',
],


How to alter a form element to include it inside a fieldset

This code might help you out.

   $form['date_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('Select Start and End dates'),
        '#collapsible' => TRUE,
//        '#tree' => TRUE,
    );

    $form['date_fieldset']['date_inactive_start'] = array(
        '#title' => t('Start date'),
        '#type' => 'date_popup', // Provided by the date_popup module
        '#date_format' => 'd/m/Y',
        '#date_year_range' => '0:+1',
        '#required' => TRUE,
        '#size' => 8,
        '#default_value' => date('Y-m-d', time()), // Default value must be in 'Y-m-d' format.
    );

    $form['date_fieldset']['date_inactive_end'] = array(
        '#title' => t('End date'),
        '#type' => 'date_popup', // Provided by the date_popup module
        '#date_format' => 'd/m/Y',
        '#date_year_range' => '0:+2',
        '#required' => TRUE,
        '#size' => 8,
        '#default_value' => date('Y-m-d', time()), // Default value must be in 'Y-m-d' format.
    );


Integrate external DB users via their API in Drupal 7

In order to implement external authentication you need to alter the login forms (user_login and user_login_block) to alter their validation handlers.

The default validation handlers for the forms are user_login_name_validate(), user_login_authenticate_validate() and user_login_final_validate(). You will need to replace user_login_authenticate_validate which is used to check the supplied username/password against local users table. Your replacement should invoke your API to handle the authentication.

Depending on your need, you may want to provide automatic registration (on the Drupal site) of new user on authentication. In such as case, you can use the user_external_login_register() function to create the account from your user_login_authenticate_validate replacement.

To map the Drupal user to the user on the external system, Drupal provides the user_get_authmaps() and user_set_authmaps() functions. Note that that user mapping mapping is automatically handled when using the user_external_login_register() and user_external_load() functions.

The perform your HTTP requests, you can use the drupal_http_request() function which usually do the job and support HTTPS. Of course, you can also use another HTTP library.

All of this will have to be done in a custom module and you will need good understanding of Drupal's Form API.

A comment on the documentation page for user_external_login_register() provides detailed explanation of the complete process.

Note: The Services module is useful when you need a read/write HTTP-based API for your Drupal site's data. In your case, it would not be usefull since you need to consume an existing API to authenticate the users.


How do I manipulate a variable's property in Twig?

{% doesn't render, and merge doesn't operate by reference. With those two things in mind, this:

{% content.my_link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}

does nothing, except to waste CPU cycles; you're not rendering, nor saving, the result of the merge.

There are various ways to solve, this is probably the simplest:

{% set link = content.my_link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}
{{ link }}


use EntityFieldQuery to find user based on profile field value

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_user_payroll', 'value', $payroll, '=');
$results = $query->execute();

$users = user_load_multiple(array_keys($results['user']));
foreach($users as $user) {
    $wrapper = entity_metadata_wrapper('user', $account);
    $mimemail = $wrapper->mimemail->raw();

    watchdog('Photo Import', "Mimemail: %mimemail", array('%mimemail' => $mimemail), WATCHDOG_INFO);
}

as per EntityFieldQuery::fieldCondition(), EntityFieldQuery doc

......


How do I use Views Global Filter with Geofield 2.x Exposed Proximity Filter?

Add a filter that precedes that filter that is not exposed and creates the initial filter you want. Usually you can do this with most views handler filters, so it should work with the proximity filter.


How to display a menu items for a node but not for it's parent

you could use Menu blocks and play a bit with the "Visibility settings"


How to get the Route object from an URI?

You can retrieve this information from the Symfony router. This can be accessed in Drupal through the router.no_access_checks service.

If you have a simple path (note that the path has a leading slash):

$router = \Drupal::service('router.no_access_checks');
$result = $router->match('/node/2');

If you have a Url object:

$router = \Drupal::service('router.no_access_checks');
$result = $router->match($url->toString());

This will return an array that includes the route object, as well as other useful information such as the route name and route parameters, the controller, the title callback and even the entity object represented by the URL.


How to have the autocomplete option with ajax in a text field?

You need to filter the user input and return the matches.

  public function handleAutocomplete(Request $request) {
    // Getting the user input.
    $string = $request->query->get('q');
    // Getting the languages.
    $languages = \Drupal::languageManager()->getLanguages();
    // Getting the matches.
    $matches = preg_grep("/$string/i", $languages);
    // Returning the matches.
    return new JsonResponse($matches);
  }


Date popup form field doesn't show the default value correctly

Clive was absolutely right: The default value MUST be set using the date format "Y-m-d", such as with date('Y-m-d', $date).

The difference is that I used "Y-M-d" instead of "Y-m-d" for #default_value.


Remove disabled menu links from menu settings

Never solved this, finally i deleted the drupal site and rewrote the site with dogescript.


TL;DR: The hook is correct, but $node->content['mymodule']['#items'][0] should at least contain one of these array indexes/properties: "#markup" or "#theme"; if you don't use one of them, Drupal will not output anything.

If the array indexes you use are for properties handled by your theme function, then you should use # at the beginning; for example "format" would become "#format" (the same is true for the other properties).

Anyway, there is no need to use "format" as you do (whatever meaning it has); the function just output HTML, as done in the example shown in the hook_node_view() example.

function hook_node_view($node, $view_mode, $langcode) {
  $node->content['my_additional_field'] = array(
    '#markup' => $additional_field,
    '#weight' => 10,
    '#theme' => 'mymodule_my_additional_field',
  );
}

If you want some more concrete examples of that hook implementations, you can look at book_node_view(), statistics_node_view(), and translation_node_view().

function book_node_view($node, $view_mode) {
  if ($view_mode == 'full') {
    if (!empty($node->book['bid']) && empty($node->in_preview)) {
      $node->content['book_navigation'] = array(
        '#markup' => theme('book_navigation', array('book_link' => $node->book)),
        '#weight' => 100,
      );
    }
  }

  if ($view_mode != 'rss') {
    book_node_view_link($node, $view_mode);
  }
}

As side note, I will add that you should use the # character only for properties, or you are going to confuse Drupal, which expects that character to be used only for properties.
In fact, element_children(), which returns the list of child elements of the element passed as argument, uses the following code:

  foreach ($elements as $key => $value) {
    if ($key === '' || $key[0] !== '#') {
      $children[$key] = $value;
      if (is_array($value) && isset($value['#weight'])) {
        $sortable = TRUE;
      }
    }
  }

As you see, elements whose key value starts with # are not taken to be child elements; differently, Drupal would not be able to handle a case like this one (the code is really implemented by a Drupal module, the Search module):

  $form['#action'] = url($action);
  // Record the $action for later use in redirecting.
  $form_state['action'] = $action;
  $form['#attributes']['class'][] = 'search-form';
  $form['module'] = array(
    '#type' => 'value',
    '#value' => $module,
  );
  $form['basic'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('container-inline')),
  );
  $form['basic']['keys'] = array(
    '#type' => 'textfield',
    '#title' => $prompt,
    '#default_value' => $keys,
    '#size' => $prompt ? 40 : 20,
    '#maxlength' => 255,
  );
  // processed_keys is used to coordinate keyword passing between other forms
  // that hook into the basic search form.
  $form['basic']['processed_keys'] = array(
    '#type' => 'value',
    '#value' => '',
  );
  $form['basic']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
  );

Are $form['#action'] and $form['basic']['submit'] child elements?

As another side note, I will add that hook_view() is invoked by Drupal only for the modules that implement a content type.
In fact, the implementations of that hook are invoked by node_build_content() using the following code:

  // The 'view' hook can be implemented to overwrite the default function
  // to display nodes.
  if (node_hook($node, 'view')) {
    $node = node_invoke($node, 'view', $view_mode, $langcode);
  }

The code for node_invoke() is the following one:

  if (node_hook($node, $hook)) {
    $base = node_type_get_base($node);
    $function = $base . '_' . $hook;
    return ($function($node, $a2, $a3, $a4));
  }

The code invokes $hook for the module implementing the content type of the node passed as argument.


How to make user picture editable without opening edit profile page?

You would have to write your own form where a user can upload the picture and save it as profile picture.


buildForm runs before ajax button's submit handler on first click

Yes, this the normal behavior. In D7 and earlier in Drupal 8, having a form with at least one #ajax element forced the form to be stored in "cache", which quickly resulted in a huge amount of data there (we had GB of data in key_value_expire in an very early D8 site and it was growing almost faster than we could keep deleting it)

Now this only happens on the first Ajax request, when the form actually needs to start storing data.

The only thing you can do is depend your key on something that is more or less stable, you're possibly editing something that has an ID or you have a loop displaying multiple forms, then you can pass in an index. In Simplenews where we display multiple forms in blocks and we generate a unique Id (or allow the user to provide one) that we can then use to identify the forms.

Note that you need a unique form_id anyway to be able to use the same form more than once per page, see Generate unique form ID based on context.


Proper approach for showing menu based on node

I'd say the best way would be to use Menu Block.  This would allow you to use blocks built in visibility rules.

All you would need to do is create a new menu block, select which menu to display and select which content type it should be displayed on.  The menus get all the functionality of standard menus.

You could also just use the standard block that is created with every menu, check the disabled blocks section for those.  Menu Block however has a few more features.


Get cart items and check for product of type X

Well this seems to work!

global $user;
$order = commerce_cart_order_load($user->uid);
$wrapper = entity_metadata_wrapper('commerce_order', $order);

foreach ($wrapper->commerce_line_items as $delta => $line_item_wrapper) {
  $type = $line_item_wrapper->commerce_product->value()->type;
  if($type=='X'){
    //perform a task
  }
}


We have successfully integrated Drupal with DSM using LDAP project: https://www.drupal.org/project/ldap

Basicall DSM is running OpenLDAP which is supported by the project. Be sure to enable php-ldap extension.

The ldap module distribution comes with a set of submodules that you enable to configure LDAP authentication and authorisation:

ldap_servers - define LDAP server
ldap_user - Sync users (User entity fields to LDAP attributes) with LDAP
ldap_authentication - Allows user to authenticate with their LDAP username/password
ldap_authorization - Give Drupal users roles based on LDAP group.

It also provides a comprehensive GUI to visually configure everything. Also integrates with 'devel' to debug.

HTH


How do I change assigned redirect url to drupal root url?

Fixed.........
You just have to reset the base url ($base_url = 'http://www.example.com';) in your main settings.php file to whatever your desired url is and refresh the page... It should work fine afterwards.

Thanks anyways.


How do I change the structure of node's $content variable?

Creating a template (node-MyContentType.tpl.php) for your content type is certainly helpful to manipulate the display of the entire node, but it sounds like what you're looking for is how to modify individual fields, and these are rendered in a different template.

Drupal uses template files and theme_xxx() functions to display elements on the site, and there is generally one template or theme function for each object (page, node, block, field, etc.). In order to override them, you use a feature called Template Suggestions. These are an alternate template (.tpl.php) file that you have created to override the base or original template file. Read more about these for Drupal 6 or Drupal 7.

The best way to create your own version of a template file is find the original one, copy it into your theme folder (don't modify the original!), and rename it using the "template suggestions" convention mentioned in the links above. In Drupal 6, you have to have both the base template (e.g. node.tpl.php) as well as the renamed one (e.g. node-mytype.tpl.php). In Drupal 7, having the base template in the same folder is not necessary.

In Drupal 6, fields are a part of the CCK module. Here's information on overriding CCK Field templates. The original template content-field.tpl.php is located in the CCK module under cck/theme.

In Drupal 7, fields are a part of the Drupal core code. The original template field.tpl.php is located in modules/field/theme.


The best practice is still to use Drupal's behaviors system even when not relying on jQuery. See Drupal 8 Drupal.behaviors without jquery for reference.

That said, I think you're on the right path. I find jQuery just slows down the page load when vanilla JS will usually do the trick. That's just my opinion and there's a lot of debate out there.


Print registration and login forms on same page

print(drupal_render(drupal_get_form('user_register_form')));
print(drupal_render(drupal_get_form('user_login_block')));

See user_register_form() and user_login_block() for details. Note that user_register_form is an unusual form builder function: it redirects in some cases.


Create a block (navigate to Structure -> Blocks -> Add block or http://example.com/admin/structure/block/add)
Make sure you set the Text format of the block to "Full Html"
Paste in your embed code

Please be aware of the security risks involved http://example.com/admin/help/filter, https://drupal.org/node/213156


I came across a similar issue and found your post last week. After a bit of searching around I found this module:

https://drupal.org/project/track_field_changes

It appears to cover what you were looking for in terms of functionality as well as what I was trying to cover. I've since installed the module and set it up, but unfortunately whilst some of it is working for me I can't get a view to display the 'value after' or 'value before' fields (See https://drupal.stackexchange.com/questions/81507/how-to-display-values-in-the-value-after-value-before-fields-track-field).

If you still need this functionality perhaps try out the module - if you have success with it let me know as it's still not quite working fully for me, but that could be down to user-errors perhaps.

All the best

Tom


From https://github.com/drush-ops/drush-launcher#xdebug-compatibility:

  Drush Launcher, like Composer automatically disables Xdebug by default. This improves performance substantially. You may override this feature by setting an environment variable. DRUSH_ALLOW_XDEBUG=1 drush [command]

So to make Xdebug reach the rest of your code, add DRUSH_ALLOW_XDEBUG=1 to the environment variables in front of your command.


Dynamic menu linking to the forum associated with the current Organic Group

You do this with contextual filters. In the forum view, under the advanced settings, go to relationships and add OG membership: OG membership from Node. Then add a contextual filter OG membership: OG group gid. You will also need a default argument for "When the filter value is not in the url". You will use "Current OG group from context" for that. Rearrange your contextual filters if necessary so that is the first one.

Then in your page settings, set the path to group/%/forum (or whatever the correct path to your group page is). The % will be expanded to the group id, so that group/1/forum will show you the forum view for the group with gid=1.

You can then set the menu option just below the path option. That will put the menu on any page in the path you set.

Give that a try.


What is an alternative to hook_node_view()?

If you are just editing one field you can use template_preprocess_field(), hook_field_display_alter(), or hook_field_display_ENTITY_TYPE_alter(). Those should also fire in other contexts if you use that field outside the panel pane in the future (which may be a good or bad side-effect depending on your context).


Panel content page not displaying correctly after restoring backup on different server

First, before doing anything else, try clearing all the Drupal caches.

Then, if that doesn't do the trick, you need to make sure that you restore your files as well as your database.  Adaptivetheme and Panels both save some of their settings in files (for example, Adaptivetheme saves the color information of the theme); if you restore the database without the files, your site will behave strangely until you restore the files as well.

Alternately, if for some reason you do not have a copy of the files, you can re-save the theme settings by going to Appearance -> Theme name -> and then scrolling down to the bottom of the page and clicking "Save," which will cause Drupal to regenerate the theme files.


Adding attribute to menu - page specific

found it,

$page = arg(0);

cheers anyways


What replaced the ContentFormControllerSubscriber class?

It was renamed once or twice, but https://www.drupal.org/node/2613034 moved the actual code from an event subscriber to a route enhancer. See \Drupal\Core\Routing\Enhancer\FormRouteEnhancer for the current approach.

Good event subscribers will document how they determined what priority to use, it could have been random or very carefully picked.

See CTools' \Drupal\ctools\EventSubscriber\WizardControllerSubscriber which still uses 29.


visibility of a view based on current node field

Just add another filter on the parent node relationship for that current field.  Not sure on what field is what for you but it seems you have all the relationships added into the view based on the parent node page?

Just add another filter, select the field you want to check, add the parent node relationship and make sure its NOT EMPTY.

If you just have the contextual filter as a nid, add a relationship to that nid so you can get access to the parents fields.


How to add existing taxonomy terms to node on saving

The only place you need to add values in your hook_form_alter() is the $form_state['values'] array. In there you should only see the tid value, not the whole term entity.

Alternatively, you can use the Rules module


Programmatically added comment form on node page doesn't work

I'm not sure about the failure to submit, but drupal_get_form caches the form config, so making changes to the #redirect after calling it will be lost by the time the form submits. You'd need to use hook_form_alter for that change to persist.

As an alternative, you might consider the AJAX comments module. In theory that will work with a manually embedded comment form, and it'll sidestep your current issue while providing a slightly better UX for comments site-wide.


How to send an eMail to registered users after they are invited using the Group module?

You can use the Rules module to achieve that "people who already have a user account, also receive an email invitation in addition to the invitation on their user account" (as in your question).

Here is the rule (in Rules export format) to actually do so:

{ "rules_send_email_after_inviting_a_registered_user" : {
    "LABEL" : "Send eMail after inviting a registered user",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "group" ],
    "ON" : { "group_membership_insert" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "group-membership:status" ], "value" : "invited" } },
      { "NOT user_has_role" : {
          "account" : [ "group-membership:user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[group-membership:user:mail]",
          "subject" : "You have a pending group invitation",
          "message" : "Hi there!\r\n\r\n[site:current-user:name] has invited you to become a member of the group \u0022[group-membership:group]\u0022 on [site:name].\r\nIf you wish to accept the invitation, you need to login with your existing account first, which is \u0022[group-membership:user:name]\u0022.\r\nPlease visit the following address in order to do so: [site:login-url]\r\n\r\nKind regards,\r\nThe [site:name] team",
          "from" : "[site:current-user:mail]",
          "language" : [ "" ]
        }
      },
      { "drupal_message" : { "message" : "You just invited existing user with name [group-membership:user:name] and eMail Id [group-membership:user:mail] to the group named [group-membership:group].\r\n\r\nAn appropriate message about this invitation just got eMailed to [group-membership:user:name] also." } }
    ]
  }
}

Some more details about the magic included in this rule:

Sending an invitation in the Group module's terminology is equivalent to inserting a new Group Membership with status "invited" (how easy can it be?). So that explains the Rules Event I'm using, and the first Rules Condition.
Since we only want to send such eMail to users who already have an account, the 2nd Rules Condition is to check that the invited user does NOT (!!!) have role anonymous.
The Rules Action is just to send an appropriate eMail, using specific tokens related to the Group Membership, etc.
For debugging purposes, the 2nd Rules Action shows a confirmation message about the triggered eMail (feel free to remove that action if you don't like it).

Just import the above rule (using the Rules UI) in your own site, with no customization (changes) needed to see it at work in your own site (don't worry, there is no spyware in the eMail being produced ...).

The eMail content is pretty close to the eMail delivered when inviting anonymous users (the only difference is that it has an instruction to login with their existing account, also included in the eMail body). Here is how a sample eMail body looks like:

Hi there!

Pierre.Vriens has invited you to become a member of the group
"Drupal for Sitebuilders" on www.example.com.

If you wish to accept the invitation, you need to login with your existing
account first, which is "Dries.Buytaert".

Please visit the following address in order to do so:
http://www.example.com/user

Kind regards,
The www.example.com team

Possibly you may want to finetune the eMail subject, or eMail body. But apart from that no other changes should be needed.

Voilà ...


hook_field_formatter_view not being called

Whelp, there goes an hour.

Turns out I was configuring the "Default" Display rather than the "Full Content" Display.


Drupal Commerce: Can I split payment over multiple credit cards?

No

It is not possible now. It was requested, and it is Closed (won't fix) - if you want it, you need to code it yourself.

  This isn't something Commerce can do out of the box, and I'm not entirely sure it would fit in. However, in a contributed module, you should be able to look at the order balance before moving forward to the checkout completion page and requesting additional payment from the customer if necessary. For now, I'm just going to have to mark this "won't fix" as no easy ideas come to mind for how we could make this abstract enough to solve in core. The main problem in core would be how you visualize the outstanding balance and accommodate both on-site and off-site payment methods.


How to merge posts from 5 different website and import one post to drupal by feeds

1) Create one content type with title and download file link with unlimited or five number of values can be added.

2) Get the fed from 5 sites for one particular title and create the node respective title and fill the 5 respective download link.


Convert a static query to dynamic one, with a having clause

If I understand you right you just need to use the having() member function of the SelectQuery:

$query->having('count(po.oid) > 0');

FYI you have this line twice:

$query->condition('pa.nid', $nid);

I don't think it'll make a difference to the query result but it's probably best to remove the duplicate line.


Have you check the Scald module?
This is a real alternative in active development.

  Scald is a different take on how to handle media (audio, video, image or otherwise) in Drupal and beyond. It is a platform designed to make it extremely easy to implement the social features which are so essential -- and so unique -- to web communities. Additionally, Scald -- in tandem with the DnD module -- provides a novel and natural way for users to compose complex posts.

Feel free to ask me for details, or to put a issue in the module issue queue.


I have few thoughts about this situation:

Controllers should not contain business logic, services should. Therefor unit testing a controller is not a good idea in the first place.
If you are unit testing your controllers "getResource" method, why do mock the controller itself? You should mock the HttpClient. (that's the strong part of DI)
First you mock the classes which your constructor needs as arguments. Then you just create your object, which will you test like this: $example_controller = new ExampleController($http_client_mock); And that's it.


Print a block inside a Views header or Views footer using PHP input

Try this module https://www.drupal.org/project/views_block_area - it allows insert any block into the view's header or footer.
Another way using code

$blockObject = block_load('module', 'delta');
$block = _block_get_renderable_array(_block_render_blocks(array($blockObject)));
$output = drupal_render($block);
print $output;


Undefined variable error in node.tpl.php

If you want to get rid of this notice, replace your line 33 with:

<?php if (isset($comment_count)) print $comment_count; ?>


if you want to use AMP for specific pages, you might want to take a look at the AMP module.

But if you still want to add the amp attribut to the <HTML> tag manually, here's one way:

Overwrite the html.tpl.php template by copying the original tpl file (modules/system/html.tpl.php) to your current theme (sites/all/themes/your_theme/). Then add the following code at the top of the file:

$amp = '';
if (arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
    $node = node_load($nid);
    $amp = $node->type == 'ir_news' ? 'amp' : '';
}

Then, you just print the $amp variable inside the <html> tag.

The amp attribute will only be added to your ir_news pages.


How to COMPLETELY limit access to Views pages?

That is because Drupal, when users access a page to which they don't have access, it draws the page using its template file, and replaces its content with the error message.

What you can do is setting a page to use for the access denied page, and use a different template file for that page. In Drupal 7, that is done in admin/config/system/site-information, under Error pages.

Keep in mind that, when an access denied error is returned, the URL of the page is not changed; this means the users would still know the node has a calendar attached, if they try to access the page using the URL directly. The Calendar tab is not shown to users who don't have the permission to access it, though; they can only try using the tab URL, and see if they get an access denied error.