How do I programmatically populate longitude and latitude fields when Geolocation used in content type

Pretty straight forward just had to change the field names to correspond with the field names used by Geolocation:

$node=Node::create(
  'type' => 'content type - machine name',
  'title' => 'Shop 1',
  'geolocation_field' => ['lat'=> 1, 'lng' => 2.33]
);
$node->save();


Can I find the term depth via $node without resorting to a taxonomy_get_tree or an SQL query?

The data for taxonomy is in the database. If you want to get that data there is no way to do so without running a database query.

Any function that retrieves this data (including taxonomy_get_tree() and the function you link to above) has to run database queries to get at the data.

taxonomy_get_tree() is a bit heavy so I'd advise using the term_depth function you link to. If you want to increase performance slightly you can improve that function to offer a static page load cache. This will only make a difference if you call the function more than once in a single page load though:

function term_depth($tid) {
  static $depths = array();

  if (!isset($depths[$tid])) {
    $parent = db_result(db_query("SELECT parent FROM {term_hierarchy} WHERE tid = %d", $tid));
    if ($parent == 0) {
      $depths[$tid] = 1;
    }
    else {
      $depths[$tid] = 1 + term_depth($parent);
    }
  }

  return $depths[$tid];
}

Short of building your own cache mechanism that doesn't rely on the database (which would be a massive amount of overkill for this situation) I don't see any way of making this more performant.


You need to use the Variable Translation for that:

  In Configuration > Regional and languages: Multilingual settings > Variables, enable 'Default front page' as a multilingual variable.
  Go to Configuration > System > Site information > Front page.
  Change the language via the section "Select language" at the top of the page to select the language for which you're setting the front
  page option.
  Set the 'Default front page' option for the current language.
  Repeat as necessary for each available language.

Relevant link: HowTo: Different home page (default front page) for each language


create list of  content titles at end of each articles

Create a views display in which you'll show complete node and add an attachment to display which'll show the titles of all the other nodes.


Get single edit field from a content type

You can build a custom autocomplete text field to filter node reference results. Check this link http://timonweb.com/how-create-ajax-autocomplete-textfield-drupal-7 to build autocomplete text field.

You just need to change the query in above implementation.


In some cases it can depend on how and where you have added your CSS to the page.

The best way to do it is using #attached on your field via hook_form_alter() or similar.

If your CSS is already on the page though it should work on new elements added with ajax.

One possible cause is that your CSS selectors are too specific and the ID/class used isn't matching properly with the markup added by the ajax.


SQL select data from more than one table

You second query is incorrect because you have the table field_data_field_group_category two times, so it would generates duplicates and there's a missing coma in your SELECT clause. If you want your column in the result without filtering it, just put it in the SELECT clause and that's it.

SELECT og.label AS title
  , og.gid AS gid
  , field_data_field_group_category.field_group_category_value AS cat
FROM og
LEFT JOIN field_data_field_group_category
  ON og.etid = field_data_field_group_category.entity_id
ORDER BY title ASC


How to programatically get the product id of newly added product using the commerce form

Provided that your additional submit handler is invoked after default one (which by looking how you added it, is the case), you can access nid of the node created as follows:

function my_module_redirect_handler(&$form, &$form_state) {
    $node_id = $form_state['values']['nid'];
}

Now that you have nid you should be able to do required processing.

Hope that helps.


How to use drupal_add_library with a module?

You can call it in that hook if you want it on every page (or add some logic to restrict the pages that it loads on), that's fine.
As per the API:

$module: The name of the module that registered the library.
$name: The name of the library to add.

If you're creating your own library, Jimmy Ko is correct: you need to declare it in hook_library.
Note that $name should exclude the file extension (e.g. .js)


After a lot of debugging, I finally managed to make this work. The trick lies inside $form['complete form']. but first things first, how does form_set_value() work and what does it do?

The form_set_value() function

As the documentation suggests:

  If you want to update the value of $form['elem1']['elem2'], which should be stored in $form_state['values']['elem1']['elem2'], you would set $element['#parents'] = array('elem1','elem2').

Now what does that mean? In my case, I had a textfield called 'field_event_title', which is the name I gave it on creation. In $form, all fields have a sub-array in $form['field_name'], which in my case is $form['field_event_title']. This is where the submitted value also is stored. Since it is a textfield, Drupal maintains both the language and the delta [question for editors: is this right?] of the input data. So in fact, the value is not stored in $form['field_name']['value'], but in $form['field_name']['und'][0]['value'] (['und']=language; [0]=delta). Note that "und" is the Drupal key for the default language of the site; if it is in German, then it would be "de"; however, in most cases it should be "und."

To actually change the value using form_set_value(), one is ought to invoke the function by writing:

form_set_value($form['field_name'], array('und' => array(0 => array('value' => 'foo'))), $form_state);

Updating a form to repopulate it with different values than submitted (or clearing them)

Thus far, this was what Krister Andersson suggested, but that did not work in my case, since I wanted to clear fields once a custom validation error has been invoked. One would suspect that the form repopulates itself using the values inside $form_state['values'] (which is actually the place where the values are stored, the actual place that gets updated when using form_set_value() and the place which generates the $form later), but that is not the case: It uses the values inside $form_state['complete form'], which is a 'copy' of $form (notice that it is spelled 'complete form', with a space, not an underscore).

Using $form_state['complete form']['field_name']['und'][0]['value']['#value'] = 'foo'; is what updates the values that actually repopulate the form on a validation error. (Note: you can, as do I in my usecase, set it to =NULL to simply empty the field.)

Summary

Where is the difference between $form['field_name'] (e.g. updating through form_set_value()) and $form['complete form']? Well, the former updates the actual value, which then gets stored inside the database; the latter is being used to repopulate a form when it failed a validation.


When users create an account, and the email verification has been set as required, the value of the "status" field is set to 1 right after the users enter the username they want to adopt and their email address, if users are allowed to create an account without the approval of an administrator user; the "access" and "login" fields will be 0, until the users don't log in, which happens also in the case they follow the link reported in the email message sent to verify the email address they reported for their account.


custom action plugin with ConfigurationForm

You need to install the core module Actions first to be able to configure action plugins in UI.
Then you can access the actions overview page:
/admin/config/system/actions
On the top of the page your new plugin should be present in the select list for creating advanced actions. When you select the plugin you should see the configuration form of your plugin:
/admin/config/system/actions/add/action_plugin_examples_update_node_title
Since you have already provided an action configuration in a YAML file you should also see a configured instance of your plugin in the available actions list.


Which link field accepts an URL or a Node reference?

In Drupal 8 this works with normal link fields. You simply can choose if only internal, only external or both type of links can be entered in this field. You'll then get a autocomplete field that accepts either an entity title or an external link and a title.


Multiple node references using url-widget

You can put in the number of values that goes into the reference field, i.e. number of references to other nodes, as part of the content type definition (manage fields). That is at least the case Node Reference. You can also select which content types that can be selected. So pick the content types you need and select how many that the users should be able to pick.


The easiest way would be to override the nd_regions.css file in your theme and put something like the following in it:

.nd-region-header,
.nd-region-footer {
  clear: both;
}
.nd-region-left {
  width: 50%;
  float: left;
}
.nd-region-right {
  width: 50%;
  float: right;
}
.nd-region-middle-wrapper {
  display: none;
}

Simply don't put anything in the DS middle column, manage a gutter and you'll be fine.


how to retrieve refrencing parent id with EntityFieldQuery

Without extending the class I'm pretty sure not. The reverse relationship isn't defined as a field, so EntityFieldQuery won't be able to help.

Don't forget entity reference doesn't define a parent/child relationship, it's literally just a relationship from one entity to another. A single entity can be referenced by any number of other entities, so the notion of a single 'parent' doesn't conceptually exist.

If you want more advanced relationships you might consider converting to the Relation module. It has a RelationQuery class which wraps around EntityFieldQuery to add relationship-specific functionality.


There's no such hook as hook_node_save(), you're probably looking for hook_node_presave()

  Act on a node being inserted or updated.

Also, the nody body is a field so you have to treat it as such when assigning values:

function mymodule_node_presave($node) {
  $node->body[LANGUAGE_NONE][0]['value'] = 'test string';
}


You can use a view to display the search results, and exposed filters for the search box.
You should set exposed filter of this view as block (in the view settings). Then you can set the form above the search results.


You don't have to define a uri/URL callback.
Defining one won't make your entities visible to users, you have to create a menu callback to make them visible.


The code you wrote doesn't work because you are using a placeholder in the definition of the menu callback; such placeholders can be of two types:

anonymous placeholder. The placeholder is just %, which matches any string.
named placeholder. In this case, the placeholder is similar to %node, %user, used from Drupal core modules. If the placeholder is, for example, %node, Drupal will look for the node_load() function, and will pass it the string that in the path replaces the placeholder; when the function returns FALSE, then Drupal will return a 404 error page to the user. As the string following the % is used as name of the load function, to which the string "_load" is appended, characters that are not allowed in a function name are discarded (PHP cannot have a function with a name like .atom_load().

If your purpose is to define a menu callback for your module that returns an atom feed for the node, then I would define the callback as the following:

$items['node/%node/atom'] = array(
  'title' => 'atom node feed',
  'page callback' => 'atom_node_feed',
  'page arguments' => array(1),
  'access callback' => 'user_access',
  'access arguments' => array('generate atom feed'),
  'type' => MENU_CALLBACK,
);

The page callback will get the node object as first argument, not the node ID.

To create a path like http://drupalsite/node/20.atom, you need to create a path alias.
You can assign path aliases using the administrative page at admin/config/search/path (Drupal 7) or admin/build/path (Drupal 6).
Using Drupal 7, a module can create a path alias calling path_save().
You can also use Pathauto to automatically set path aliases for nodes. The module uses tokens that allows to dynamically create path aliases that follows a defined schema. As far as I know, node path aliases are just set for paths like node/1; the path alias is not set for a path like node/1/edit, or node/1/atom.


What does the 'version' keyword mean in .libraries.yml?

Why should I use it?

It is used as an identifier for your libraries. Just like any project/package is tagged in different versions. For eg: jQuery 3.5.1 is slightly different from 3.0.0. The difference could be anything, from API change, new features, bug fixes, etc. Thus we need a way to identify the changes that happened to our library we created. So that we can make some conscious decisions. Another example. Suppose there is a 3rd party js that is having issues with another library of a specific version. So during the install, we can check if the other library has library greater than required.

When should I change its value?

Ideally after every deployment if any change to the library has occurred.
So what Drupal does is, it happens the version number to each file in that library when attaching that library to any page. For example: if my library has a css file called custom.css and the version number is say 1.0.0. So, the way it will get attached to the page will be like /path/to/theme/css/custom.css?v=1.0.0.
This is so far ok. But ideally on prod environments there are reverse proxies which caches these files. Suppose if we make any new changes to these files and even if we clear the cache, the files will still be served from CDN, thus we also need to make sure if any change has happened on these files, it makes sense to also increase the library version number. Just as you would do with creating a new tag for a new release for any project.
If we give the version as VERSION. Then drupal sets its version = \Drupal::VERSION the current drupal core version.


Yes - this is possible with the great views support in the Leaflet module you are using:

https://www.drupal.org/node/1645460

I'm assuming that you are using Views to render the above map given the number of data points you are displaying (and if not you should consider it). If so, then the easiest way to do this would be to edit your view, and add an 'attachment' display based on the same arguments that you are using for the above view (including the contextual filters you are using) and then change the display format to whatever you want (ex. an html list, a table, etc.) Attach this to your map view (display below) and you're all set.

Another option would be to do the same but render it as a block display instead and then place this using context or block admin to place this right below your map view.


Which folders/files in drupal 6 need not executive permission?

All folders need +x perhaps you're referring to +w ? In which case, only the files folder e.g in /sites/default/files needs to be +w by the webserver. All other folders can be owned and writeable by root only.

Here's some find commands to recursively chmod the file/folder permissions correctly

;Change all directories to 755 (-rwxr-xr-x):
find /var/www/mysite -type d -exec chmod 755 {} \;

;Change all files to 644 (-rw-r--r--):
find /var/www/mysite -type f -exec chmod 644 {} \;

;Change ownership of files directory and files to webserver user, e.g www-data
chown -R www-data:www-data sites/default/files

Update: example nginx conf to disallow .php file access in the files directory:

# Do not attempt to serve php files within sites/default/files
location ~* ^/sites/default/files/.*\.php$ {
    return 404;
}


Once your features are overridden, then the configuration is moved from the files to the database (i.e. Drupal no longer looks for the configuration supplied by the feature module and uses your configuration in the DB). This means you can update the files without overriding your changes/additions (Just don't hit the revert button in the Features admin UI). That being said, if you changed/updated a content type, you will no longer be able to take advantage of any changes/updates that were made to the commons distro supplied content type. This is the same for views, contexts, rules, etc.  Some devs will use the Features Override module to allow them to store their site specific overrides in a feature.  This allows you to store your overrides in files and still leverage any changes/additions from the distro.


Display Special Characters in Drupal Forms API

I suspect you need to add <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> into html.tpl.php in your theme. This isn't an issue with Drupal, but your browser not recognising the UTF8 characters.


Views Slideshow Contextual Filter, Show Images From Same Node

To add a contextual filter for Content:Node:Nid, configure the 'When the filter value is NOT available' by selecting 'Provide default value, and under 'Type' select 'Content ID from URL'.

Save your view and you are done.

In your case, check for the nid or entity id associated with the attached (associated) images, and relate this to the node id in the URL. If your base table is node, the Content:node:nid will work. If your base table is files, you will need to use File Usage:Entity ID.


The textbow must have a size so you wont be able to make more than what your are doing now. But if your in views you can see the DBquery generate and use it on PMA to delete a greater number of users with theirs comments.

Be carefull, it's to do if you know what you are doing. I suggest to look at the query of view  because Drupal create a table for each CCK field so it's hell to figure the inner joins. If you have a doubt, make a save of your database before.


You need to increase max_allowed_packets in my.cnf file. to insert big data from cache tables. The best practice to avoid this is, never export cache prefixed tables data.


How can i publish my content with Schedule

If you aren't concerned with the "random content" portion of your question you could use the scheduler module to accomplish the task - https://drupal.org/project/scheduler which would allow you to set specific times during the day when you wanted content to be published.

If you do want it to be randomized though, you're going to need to use rules - https://drupal.org/project/rules and VBO - https://drupal.org/project/views_bulk_operations.

(I'm assuming Drupal 7)

Create a view.
Under Fields add a "Bulk Operations: Content" field. Set the number
of entities to your desired number (in this case 2.) Set it to
publish content, Enqueue the operation instead of executing it
directly.
Under Filter Criteria set it to  "Content: Published (No)."
Under Sort Criteria set it to "Global: Random (asc)"
Under Pager set to "Display a specified number of items" and choose
the number of desired items (in this case 2)
Save your view.
Now to go Rules configuration.
If you are only running cron once every 24 hours (at 13:00) you
could trigger this on cron run, otherwise you'll need to set up some
additional steps. Assuming the 24 hour cron, set your rule to
execute when "Cron maintenance tasks are performed".
Under actions click add action then select "Load a list of entity
objects from a VBO View." Select the view you just created from the
value dropdown. Click save.
Then under actions click add loop. Default variable name at the
 bottom should be "list_item." Click save.
Now click the add action button horizontal to the loop you just
 created. Select node publish content. For the "data selector" field
 use list_item from the loop above. Click save.
Run cron to test.

2 random pieces of content should publish.


Customize user registration form by adding/modifying fields in the form and handling submit function

If it is not crucial for you to have the additional fields in custom code, I would highly recommend you to make use of the fact that user is a fieldable entity and you can add additional fields easily to it via administration at "admin/config/people/accounts/fields" - this way you do not need to handle saving of the data and display of form elements.

When doing so, you can still make use of custom validation or submit handlers or fiddle with the form and fields easily using the same technique you are using - hook_form_alter and add your submit handler to do whatever logic you require.

Back to your approach — the reason why your submit function is not being called is that you are assigning a string to it instead of adding an element to the array. Try this:

$form['#submit'][] = 'module_form_submit'; (notice the empty brackets on the left side).

If you want to completely overwrite the submit functions array use this:

$form['#submit'] = array('module_form_submit'); - but this will cause that the user will not be created and data saved (unless you do that by hand in your custom submit handler), this also cancels whatever some contrib modules to with the registration form, so you might have unexpected issues.

Edit after comments:

If you do want to keep the default behaviour, but do your logic before everything, you can put your submit handler as first, as they are executed based on their order in the array like this:

array_unshift($form['#submit'], 'module_form_submit');


The function that you should use is url(). If you want to output an absolute URL you should use the following code:

function ep3_misc_node_view_alter(&$build) {
  if ($build['#bundle'] == 'work') {
    for ($i = 0; isset($build['field_tags'][$i]); $i++) {
      $tid = $build['field_tags'][$i]['#options']['entity']->tid;
      $build['field_tags'][$i]['#href'] = url('our-work', array('absolute' => TRUE, 'query' => array('tid'=> $tid)));
    }
  }
}

If you don't want an absolute URL, replace the call to url() with the following one:

url('our-work', array('query' => array('tid'=> $tid)))

check_plain() is never used to output a URL; in fact, url() doesn't use it.


Add a subquery in a WHERE condition, using hook_views_query_alter()

Ideally I think its right to use views_join_subquery. But the subquery you are using is with IN keyword is always slow and will produce same result as using a LEFT JOIN joining with node.nid field.

You can try creating a views_join and adding the url_alias table by add_field method while the node table will be the left table.

I don't have the code at the moment but you can have a look at the below links.
https://stackoverflow.com/questions/6851945/add-table-join-where-and-order-by-to-views-query-in-views-query-alter

http://www.wordpressecoder.com/2014/01/how-to-alter-views-query-with-multiple.html
http://www.yellowpencil.com/blog/last-ditch-fix-programmatically-changing-drupal-7-view


how to integrate libraries to load third party files in themes drupal?

To use a CSS/JS library with the Libraries module in Drupal, there are a number of steps:

copy the library to sites/all/libraries/my-library;
Write a small custom module, which informs Drupal that the library is available;
Add the library where's its needed, e.g. with a MYTHEME_preprocess_html hook.

I found a very nice recent tutorial with code samples here.


For adding/attaching a file to a node using code you need a file object. If you know the path of the created PDF file, just try the following code in the hook you need. I used this code in hook_node_insert for attaching a programmatically created PDF file, while creating that node.

$source_node = node_load($nid); //load your required node here.
$file_path = 'your file path';
$file = new stdClass;
$file->uid = $source_node->uid;
$file->filename = $filename; //your file name;
$file->uri = $file_path;
$file->filemime = file_get_mimetype($file_path);
// Make it permanent, otherwise it will get deleted later.
$file->status = FILE_STATUS_PERMANENT;
// Save file object to make it a 'managed file'.
$file_obj = file_copy($file, 'new path for your file', FILE_EXISTS_REPLACE);

$source_node->your_file_field_name['und'][0] = array(
 'fid'  => $file_obj->fid,
 'uid'  => $file_obj->uid,
 'filename'  => $file_obj->filename,
 'uri'  => $file_obj->uri,
 'filemime'  => $file_obj->filemime,
 'filesize'  => $file_obj->filesize,
 'status'  => 1,
 'display'  => 1,
 'description'  => '',
 );

node_save($source_node);

Hope this will help you.


Exposed filters submit with AJAX not working - regular submit instead

Found a solution. Ambidex idea is the key. My problem was that I didn't have printer classess within views-view--XXXX.tpl.php. After this everything works OK and there is something like "view-dom-id-82374yrcnuerhnw875yt3o8743y" (first line of Ambidex code) class added, which is probably needed by AJAX calls.


Alright, the problem was just plain old Javascript.

The bug made it look like the setTimeout had no delay parameter, which defaults to 0.

After looking more at it, the rotateSpeed variable was not available in the block scope of the featureRotate function, but in its closure.

So I replaced the following:

// In the featureRotate function
setTimeout(featureRotate, rotateSpeed)

With:

// In the featureRotate function
setTimeout(featureRotate, this.rotateSpeed) // Look at this magic :-)

And it works perfectly!


How to provide a contextual filter with an OR conjunction to a view?

I guess you need to use hook_views_query_alter and then you could add your OR condition.

function hook_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'machine_name_of_your_view' ) {
   //$query->where contains the filter conditions
   //i.e. 'Where' part of the query where you could add yours.
   var_dump($query->where);die;
  }
}

more from drupal.org


using an existing token as a variable in a custom token

Accessing the database to set a token is not different from accessing the database in other cases.

function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $sanitize = !empty($options['sanitize']);

  $replacements = array();

  if ($type == 'YOUR TOKEN TYPE') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'YOUR TOKEN':
          $replacements[$original] = /* CODE TO QUERY THE DATABASE */;
          break;
      }
    }
  }

  return $replacements;
}

As for accessing the value of a token defined from a module, when you know the token you are looking for, you can call token_replace() passing the token for which you want to know the value as first parameter. Keep in mind that your implementation of hook_tokens() is going to be called again; be careful of not causing a loop.


Drupal 8 :

$user = \Drupal\user\Entity\User::load($uid);
$value = $user->field_name->value;

For multiple values, use

$value = $user->get('field_name')->getValue();


Published checkbox field displaying in form footer instead of node options

NodeForm.php defaults the position to the 'footer' group:

$form['status']['#group'] = 'footer';

In a custom module or your theme, this can be set to the 'main' section:

/*
* Implements hook_form_BASE_FORM_ID_alter()
* @param     Array $form, Object $form_state, Array $form_id
* @return    Array $form
*/
function MY_MODULE_form_node_form_alter(&$form, FormStateInterface $form_state,  $form_id) {

    // NodeForm.php defaults this to 'footer'.
    // Set to 'main' so we can reposition it in 'Manage form display'.
    $form['status']['#group'] = 'main';

  return $form;
}

After this, it can be repositioned in 'Manage form display'.


In D7 what is the correct way to create a page template that has HEAD elements specific to that page?

Use hook_preprocess_html ( e.g in template.php ) to modify the html.tpl.php variables.

For different JS or CSS, check the path ( e.g current_path() == 'foo' ) and add with

drupal_add_js or
drupal_add_css

Set the 'every_page' option, and perhaps preprocess flag to FALSE.


where in database is renamed login for 'Rename Admin Paths"

Look in the config and key_value tables for "rename_admin_paths.settings"


Profile field create and set default value programmatically

Try with this

$field_instance = array(
'field_name'    => $fielddef['field_name'],
'type'          => 'list_boolean',
'entity_type'   => 'user',
'bundle'        => 'user',
'label'         => t($opts['label']),
'description'   => t($opts['description']),
'required'      => FALSE,
'widget'        => array(
    'type'      => 'options_onoff',
    'weight'    => 10,
),
'settings'      => array(
    'allowed_values' => drupal_map_assoc(range(0,1)),
    'default_value' => array(1),
)

);


So, I ended up figuring out some code that would let me do this, by creating a custom block and, in the build method, outputting the menu with transformers added to it. This is the link I used to figure out how to get the menu in the block and add transformers to it: http://alexrayu.com/blog/drupal-8-display-submenu-block. My build() ended up looking like this:

$menu_tree = \Drupal::menuTree();
$menu_name = 'main';

// Build the typical default set of menu tree parameters.
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

// Load the tree based on this set of parameters.
$tree = $menu_tree->load($menu_name, $parameters);

// Transform the tree using the manipulators you want.
$manipulators = array(
  // Only show links that are accessible for the current user.
  array('callable' => 'menu.default_tree_manipulators:checkAccess'),
  // Use the default sorting of menu links.
  array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  // Remove all links outside of siblings and active trail
  array('callable' => 'intranet.menu_transformers:removeInactiveTrail'),
);
$tree = $menu_tree->transform($tree, $manipulators);

// Finally, build a renderable array from the transformed tree.
$menu = $menu_tree->build($tree);

return array(
  '#markup' => \Drupal::service('renderer')->render($menu),
  '#cache' => array(
    'contexts' => array('url.path'),
  ),
);

The transformer is a service, so I added an intranet.services.yml to my intranet module, pointing to the class that I ended up defining. The class had three methods: removeInactiveTrail(), which called getCurrentParent() to get the parent of the page the user was currently on, and stripChildren(), which stripped the menu down to only the children of the current menu item and its siblings (ie: removed all submenus that weren't in the active trail).

This is what that looked like:

/**
 * Removes all link trails that are not siblings to the active trail.
 *
 * For a menu such as:
 * Parent 1
 *  - Child 1
 *  -- Child 2
 *  -- Child 3
 *  -- Child 4
 *  - Child 5
 * Parent 2
 *  - Child 6
 * with current page being Child 3, Parent 2, Child 6, and Child 5 would be
 * removed.
 *
 * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
 *   The menu link tree to manipulate.
 *
 * @return \Drupal\Core\Menu\MenuLinkTreeElement[]
 *   The manipulated menu link tree.
 */
public function removeInactiveTrail(array $tree) {
  // Get the current item's parent ID
  $current_item_parent = IntranetMenuTransformers::getCurrentParent($tree);

  // Tree becomes the current item parent's children if the current item
  // parent is not empty. Otherwise, it's already the "parent's" children
  // since they are all top level links.
  if (!empty($current_item_parent)) {
    $tree = $current_item_parent->subtree;
  }

  // Strip children from everything but the current item, and strip children
  // from the current item's children.
  $tree = IntranetMenuTransformers::stripChildren($tree);

  // Return the tree.
  return $tree;
}

/**
 * Get the parent of the current active menu link, or return NULL if the
 * current active menu link is a top-level link.
 *
 * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
 *   The tree to pull the parent link out of.
 * @param \Drupal\Core\Menu\MenuLinkTreeElement|null $prev_parent
 *   The previous parent's parent, or NULL if no previous parent exists.
 * @param \Drupal\Core\Menu\MenuLinkTreeElement|null $parent
 *   The parent of the current active link, or NULL if not parent exists.
 *
 * @return \Drupal\Core\Menu\MenuLinkTreeElement|null
 *   The parent of the current active menu link, or NULL if no parent exists.
 */
private function getCurrentParent($tree, $prev_parent = NULL, $parent = NULL) {
  // Get active item
  foreach ($tree as $leaf) {
    if ($leaf->inActiveTrail) {
      $active_item = $leaf;
      break;
    }
  }

  // If the active item is set and has children
  if (!empty($active_item) && !empty($active_item->subtree)) {
    // run getCurrentParent with the parent ID as the $active_item ID.
    return IntranetMenuTransformers::getCurrentParent($active_item->subtree, $parent, $active_item);
  }

  // If the active item is not set, we know there was no active item on this
  // level therefore the active item parent is the previous level's parent
  if (empty($active_item)) {
    return $prev_parent;
  }

  // Otherwise, the current active item has no children to check, so it is
  // the bottommost and its parent is the correct parent.
  return $parent;
}

/**
 * Remove the children from all MenuLinkTreeElements that aren't active. If
 * it is active, remove its children's children.
 *
 * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
 *   The menu links to strip children from non-active leafs.
 *
 * @return \Drupal\Core\Menu\MenuLinkTreeElement[]
 *   A menu tree with no children of non-active leafs.
 */
private function stripChildren($tree) {
  // For each item in the tree, if the item isn't active, strip its children
  // and return the tree.
  foreach ($tree as &$leaf) {
    // Check if active and if has children
    if ($leaf->inActiveTrail && !empty($leaf->subtree)) {
      // Then recurse on the children.
      $leaf->subtree = IntranetMenuTransformers::stripChildren($leaf->subtree);
    }
    // Otherwise, if not the active menu
    elseif (!$leaf->inActiveTrail) {
      // Otherwise, it's not active, so we don't want to display any children
      // so strip them.
      $leaf->subtree = array();
    }
  }

  return $tree;
}

Is this the best way to do it? Probably not. But it at least provides a starting place for people who need to do something similar.


Group audience versus group content visibility

The basic concept is if you don't have any access control on the content specifically then the content would inherit the groups access control. But say you had a private group that you wanted some content visible (but not all) then the access control for the content could be set to allow that to happen.

You can read more in the docs here:
Content visibility:
https://www.drupal.org/node/2014755
Group visibility:
https://www.drupal.org/node/2014751

There are even some pretty diagrams listed in the content for more help visualizing these concepts.


Views block doesn't appear on page if only media-type content is selected

The |trim twig filter in my page.html.twig was my problem as to why those blocks weren't appearing. Also, the reason that my aside always shows when that filter is removed was that in dev, it has twig debug on spitting code in that section. When twig debug is off on my production server, the aside won't appear unless content is in it and all my blocks now appear as well.


This specifically answers your question on how to override the comment links. The important part is using the value of $vars['comment_count'] to add the count into your altered link title.

function YOURTHEME_preprocess_node(&$vars) {
    if(!empty($vars['content']['links']['comment'])){
        // Get rid of other comment link with counts
        $vars['content']['links']['comment']['#links']['comment-comments'] = array();
        // Override the title of the add a comment title displaying a count
        if($vars['comment_count'] > 0)
            $vars['content']['links']['comment']['#links']['comment-add']['title'] = 'Comments ('.$vars['comment_count'].')';
        else
            $vars['content']['links']['comment']['#links']['comment-add']['title'] = 'Comments';
    }
}


My MYMODULE_config_preprocess_node(&$variables) is not displaying my variables

I think you're halfway there! The thing is that it isn't enough just to set the variable in the preprocess function, now you have to go one step further and output it in your tlp.php template file.

So, find the correct template file in your theme that you want to use (is it a general node.tpl.php one or a one for a specific content type like node--article.tpl.php), and edit it to actually output the variable you've set.

So, in the tpl.php file you're using, you should have something like:

<?php print $my_stuff; ?>

Otherwise, you've set the variable, but never display it.  Does that make sense?  Is that what's going on in your case?


Calculate the greater of two values in Rules?

I guess that you can try this to the 'numeric comparison' rule:

here is the lines used with cck fields field_test1 and field_test2:

 <?php $field1 = $form_state['values']['field_test1'][0]['value']; echo $field1; ?>
 <?php $field1 = $form_state['values']['field_test2'][0]['value']; echo $field2; ?>


Yes.

What you want is to include call drupal_add_css() for example:

drupal_add_css(drupal_get_path('module', 'your_module') . '/css/custom.css', array('group' => CSS_DEFAULT, 'every_page' => TRUE));

What that does is that it adds the css file on every page load. You can read more about adding css files here: https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_css/7

In your theme's .info file you will find a section describing where to find the css file e.g:

stylesheets[all][] = css/style.css

simply switch it off by placing a ; at the start of that line. This works particularly well if your theme is a subtheme, that is based off some other theme that you don't want to change directly in case you may need to upgrade it later.

Lastly, should you decide to remove the css file from your template.php file or module, you can do that via hook_css_alter()

for example:

function hook_css_alter (&$css) {

    if (isset ($css[path_to_theme() . '/css/custom.css'])) {
        unset ($css[path_to_theme() . '/css/custom.css']);
    }

}

Hope it helps.


Rule for allowing purchases based on country

You can use Smart IP to determine the location of the user and with the help of drupal views, you can filter the products not available for sale on that country.

That means only the products which are OK for sale in that country will be displayed to the user..


Showing popup after user registration using the "Popup message" module

Not with Popup message but this will work:

Install Rules, then create a rule with the following settings:

React on event: After saving a new user account
Actions: Show a message on the site (your message)

Drupal will show your message as a system message.


How to conditionally display field contents in Views

I have figured out a way to do what I want without the Views PHP module:
I added the link to my fields as well and rewrite the link token in my checkbox field (field_link_to_page) only if it isn't empty. That seems to have worked out well.


Make a vocabulary with states at zero level and cities at deepest level for each state. Then install hierarchical_select module.

Enjoy :)


Drupal 7.14 on IIS 7.5, MS SQL Server 10.5

Try commenting out extension=php_gd.dll in your php.ini file and try again. I found this article in which the OP had a similar problem.


How to set a taxonomy term programmatically for a node?

Use this function to get ID from Termname

function _get_tid_from_term_name($term_name) {
  $vocabulary = 'tags';
  $arr_terms = taxonomy_get_term_by_name($term_name, $vocabulary);
  if (!empty($arr_terms)) {
    $arr_terms = array_values($arr_terms);
    $tid = $arr_terms[0]->tid;
  }
   else {
    $vobj = taxonomy_vocabulary_machine_name_load($vocabulary);
    $term = new stdClass();
    $term->name = $term_name;
    $term->vid = $vobj->vid;
    taxonomy_term_save($term);
    $tid = $term->tid;
  }
  return $tid;
}


In twig you can use |batch().

For example to group the view in groups of 5 and add a div container around each group:

views-view-unformatted.html.twig

{% for group in rows|batch(5) %}
  <div class="group">
  {% for row in group %}
    <div{{ row.attributes }}>
      {{ row.content }}
    </div>
  {% endfor %}
  </div>
{% endfor %}


How do I generate PDF content from a node?

You can achieve with several solutions

Use Entity Print Module

  Entity Print allows you to print any Drupal entity (Drupal 7 and 8) or
  View (Drupal 8 only) to PDF.

  The module is lightweight compared to other modules like the Print
  module, has full test coverage and is ready to be used in production
  for both D7 and D8.

Use new host of print module (Printable Module)

  This is the new home of the print module. The module makes use of
  pdf_api module to generate PDFs.

Use PrintFriendly Module (it supports localization very good)

  The #1 Print and PDF button for your Drupal site. Printer Friendly
  pages without coding, css, or print.css. Fast, easy, and professional.

  The Print Friendly & PDF button saves paper and ink when printing or
  creating a PDF. It's fast, easy, and looks great when printed. Add the
  button now, and your users will see the difference.

  How Print Friendly & PDF Works The Print Friendly & PDF button
  automatically creates printer friendly and PDF versions of your pages
  without the hassle of having to create a print CSS file. No coding,
  hacking or programming required. Simply install the Print Friendly &
  PDF plugin, activate, and choose settings for full customization. It
  also gives your user the ability to remove images and paragraphs of
  text, so they really only have to print exactly what they want.

And final solution is kind of tricky solution, instead of converting the page to PDF just  provide a print theme style for your nodes, when a user clicks on the print button (or link) trigger  javascript:window.print() action. most of the new OS has PDF printer build-in

By the way, I recommend PrintFriendly Module


Why does Git in Cygwin complain about info/refs not being found?

From the error, it looks like your git clone line was incorrect (it complains about current_posts—which isn't a project—instead of current_content—which is). Try:

git clone http://git.drupal.org/project/current_content.git

You can also do:

git clone git@git.drupal.org:/project/current_content.git

Note that the master branch is the default branch: you don't need to specify it in the clone or afterwards: it'll automatically check it out.


Adjust viewability of content based on the value of a field for a specific user

You can just create non-admin view which display all given content types, then users can see specific content types based on their role permissions. This can be achieved by adding Nodeaccess.

For example:

user1 has role ct1
user2 has role ct2
assign view permission Nodeaccess:

ct1 role can view ct1 type, but not ct2
ct2 role can view ct2 type, but not ct1
to extend the access using field references, try: Node access node reference,

create a view which lists ct1 & ct2 and users will see the right content based on their roles.

You other few options to investigate:

in your non-admin view configure relationships, so field can point to the right content type (also check: Bundle Name Reference + EVA)
in your users's View, create sub-views where you can override the fields (if your Style is set to Fields),
create multiple views for each content type and implement Viewfield, so admin can assign the view based on the its value,
create a non-admin view with rendered entity Style, create a template, write a logic in preprocess function and assign to the template variable.


Is it a bad practice to use dynamically generated IDs for theming

It is better not to use the id.

You could use this module Block Class which allows you to add a class to the block and you can then style your css using that class.


Setting custom permissions in a view on a per-display basis

Okay, so I put this to the test, using you example. I did not experience any unexpected results. I created 3 displays and set 2 of the displays to Access:Permission | View published content. For the 3rd display, I set it to Access:Role | administrator. When I'm logged in as an Administrator, I can view all three display pages. However, when I try to view the 3rd display page as an unauthenticated user, it returns an access denied error. Displays 1-2 remain visible to an unauthenticated user.

My configuration of display 1-2:

What my view page looks like for display 1-2 (viewed as unauthenticated user):

My configuration of display 3:

View page for display 3 (viewed as unauthenticated user):

I'd double check your configuration to make sure it's correct! If you're still having issues, you could output your displays as blocks. Then you could apply permissions on those blocks using the admin/structure/block interface. You can also plug in view blocks into something like a Panel page, and apply permissions to your Panel pages.


What's the difference between these multi-site setups in Drupal 6?

I once wanted to do multisites but it became so difficult to share data without sharing ALL of the data that I stopped. I wanted to share forum content, but not page content which is impossible. It is all nodes or on nodes.

The biggest problem with doing the $db_prefix method is everything is done in your settings.php file. I shared the variables table which shared every module setting. This method then included overriding all every variable you care about. For me if was a different  google analytics code. Since this is stored in the db and I was sharing the variables table, the analytics ID was shared.

The most important table to keep up-to-date is the sequences table (auto-number table for databases that do not auto number easily) that stores the next user id to be used. If you share users, you have to have that table in lock step with the rest. It is easily edited to change the users_uid value to be the next user id in the system.

So my answer will be another question. What do you want to be shared. Users? Roles? Taxonomy? Nodes? The more you share, the more tables have to be shared and the more overhead it is.

As a side note, the documentation is very outdated. I only recommend doing this on a dev and not production copy of your database and make sure you have a backup of a working settings.php and a full backup of the drupal database. This will help to roll back and keep your site running in the event something goes wrong.

In the settings.php I have the same $db_url as all of the sites. The exception is the below items.

$conf = array(
  'site_name' => 'My Site Name',
  'theme_default' => 'my-=sub-theme',
  'site_slogan' => 'My site slogan',
  'site_frontpage' => 'my_site_view',
  'smtp_fromname' => 'SMTP Settings From',
  'site_footer' => 'Site Footer',
  'googleanalytics_account' => 'UA-112233-1',
);

Any variable inside the variables table can be set in $conf. This helps my having a different theme on my sub domain site as well as a different frontpage view. I setup a taxonomy that puts the content into the view and then out to the frontpage. I took the example frontpage view included in views and cloned it and edited it to my needs. This was a quick and dirty solution to share the nodes but keep the frontpage content separate and track each site with its own google analytics. It works but I know there are shortcomings. The major one being that content can still be searched for on both sites that does not technically belong there.


how to replace file with an empty file of the same name?

To replace a file with a zero byte file use a combination of unlink() and touch():

unlink($file_path);
touch($file_path);

To move a file to a different folder use Drupal's file_move():

file_move($src_file_path, $dest_file_path);

To rename a file use rename():

rename($file_path);

All of the above make the assumption that your webserver user has read access over the source path, and write access to the destination path.

EDIT

Your original question asked about moving/renaming files as well, I'll leave the answer to those in just in case you're still wondering.


How to display the node id as a field (with label)

Create a template for the content type and use <?php print $node->nid; ?>

Make a copy of node.tpl.php from modules/system and paste in your theme directory.  Copy the code from inside node.tpl.php and create a new file called "node--YOURTYPE.tpl.php" (replace YOURTYPE with the name of the content type).

Inside that file you can place <?php print $node->nid; ?> wherever you want the nid to be seen.  You can add a label, wrap it in HTML to style it, whatever you like. Save the file and clear the cache to see the changes.  Take a look at a node of that content type and you will see the node's nid.


I think best and easy approach would be using Flag module. You can create a Flag for user entity and grant authenticated users to flag other users, then you can check if the user is flagged as below.

$flag = flag_get_flag('ban_user') or die('no "ban_user" flag defined');

if ($flag->is_flagged($GLOBAL['user']->uid, $user->uid)) {
  // The optional second parameter to is_flagged(), which allows
  // us to ask if an item is flagged on behalf of a certain user. If this
  // parameter isn't provided, the check is made against the current user.
  print "This user has banned you!";
}


Exposed filter you can use only with views. yoursite.com/taxonomy/term/13 is not a view page. You can expose the filter as a block. And assign the block at the top of content.


Exclude a page from indexing on a per page basis

I recommend installing the Metatag module. Once installed you will have a checkbox: Prevent search engines from indexing this page located on every node under Meta tags -> Advanced.


Send email grouped on a commerce line items field

I think I found the solution to this.  I should be able to load the list of line item entities using VBO and a view grouped on the user.  I got the information needed from here:

http://nodeone.se/sv/node/777

Then I just pass the [commerce-order:order-id] as an argument.

EDIT
This worked for me.


Send a mail from my custom module after custom form submit by user

You surely can send an email on the submit.

See the code below.

function my_module_action($form, &$form_state) {
  drupal_set_message(t('Challenge Accepted'));
  $query = db_insert('challenges')
    ->fields(array(
    'cid' => '$node->nid',
    'uid' => '$user->uid'
    ))
    ->execute();
  $message = array('A new entry has been submitted');
  $to = 'example@example.com';
  $params = array(
    'body' => $body,
     'subject' => 'Website Information Request',
  );
  if (drupal_mail('my_module', 'some_mail_key', $to, language_default(), $params)) {
        drupal_set_message('Thanks, email sent.');
    } else {
        drupal_set_message('Email not sent.');
    }
}

You also need this function.

function my_module_mail($key, &$message, $params) {
  $message['subject'] = $params['subject'];
  $message['body'] = $params['body'];
}

in drupal_mail(), we pass $params array which contains parameters to build the email. If your module sends multiple emails, you can differentiate them using the $key variable.
But in this example, we simple assign message's variables from the direct $params variables.
Note that $message (in your submit handler) needs to be an array of text that you need to send.
For example,

$body = array();
$body[] = 'Hello,';
$body[] = 'There is a new submission...';

This is because when the email gets sent, body content will be imploded by a new line character. Each value in the $body array will appear in a new line.

Also, as a fine tuning, you won't need my_module_form function if you format your hook_menu function like this:

function my_module_menu() {
  $items = array();
  $items['my_module/form'] = array(
    'title' => 'My form', // We don't t() menu titles.
    'page callback' => 'drupal_get_form', // Directly call drupal_get_form...
    'page arguments' => array('my_module_my_form'), // ...with this argument.
    'access arguments' => array('access content'),
    'description' => t('My form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}


JavaScript dependencies for a specific block or page

Define an asset library in mymodule.libraries.yml. An asset library can declare either CSS assets or JavaScript assets, or both. It can also declare dependencies on other asset libraries. For example on jQuery (core/jquery) or perhaps your JavaScript defines a "Drupal behavior", in which case you depend on the supporting infrastructure for that (core/drupal). Ex:

example_library:
  js: path/to/some/file.js: {}
  dependencies:
    - core/drupal
    - core/jquery

Use #attached in your block's render array to attach the asset library:

// Assuming the variable containing your render array is called $build.
$build['#attached']['library'][] = 'mymodule/example_library';

Extensive documentation can be found at https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module.


Accessing location field programmatically in Drupal 7, via hosting entity object and wrapper

For a custom field to be available to the wrapper, the module defining it needs to implement hook_entity_property_info() (or, which is new to me, by adding property metadata to the field using hook_field_info_alter()).

The location_cck module doesn't do that, but the bundled location_entity module does.

If you enable that module you should be able to access the location field as you'd expect.


Disable comments in nodes specific taxonomy terms are attached to

For anyone not already a seasoned Rules user, here are detailed steps / a worked example for @Wheelz's approach.

This answer shows you how to enable comments when a specific taxonomy term is present and to disable them when that taxonomy term is absent. As per @Wheelz's answer it requires the Rules module. These steps have been tested against 7.x-2.2.

Create a new Rule called, e.g. 'Enable comments when tagged blog'
Add an event of the Before saving content type (use the 'React on event' dropdown and under the subdivision Node, select Before saving content). Save.
Add a condition to test for the presence of the taxonomy field that will control whether comments are allowed.

Add a condition of the Entity has field type (use the 'Select the condition to add' dropdown and under the subdivision Entities, select Entity has field)
Select node (saved content) from the 'Data selector' dropdown. (Or type node into the 'Data selector' field.) (Don't be tempted by the node:... (saved content) option. It's not what is needed here.) This specifies the type of entity for which you want to check for the presence of a field. In this case we want to check for nodes.
Select the field to check for. The dropdown will give you a list of machine names (lower case and with underscores), e.g a field labelled 'Tags' might have the machine name field_tags. (If necessary look up the machine name for the relevant field in your the 'Manage Fields' tab of the relevant content type(s).)
Save

Add a condition to test for the taxonomy term that will enable comments.

If your taxonomy field can only have one value, then select a condition of the Data comparison type. Otherwise select a condition of the List contains item type.
Select the field to test using the 'Data selector' drop down. This is a two step process. First select node:... (saved content). When you do this, the dropdown items change. Select node:<your field's machine name - but with dashes not underscores>, e.g. node:field-tags. (Don't be tempted by node:field-tags:... (Tags) - that's not what is needed here.)
Continue
If the next page isn't showing a 'Value' dropdown, click on the 'Switch to the direct input mode' button.
Use the 'Value' dropdown to select the taxonomy term for enabling comments, e.g. 'Blog'.
Save

Add an action that will enable comments

Add an action of the 'Set a data value' type.
Use the 'Data selector' to select the comment mode, This is a two step process. First select node:... (saved content). When you do this, the dropdown items change. Select node:comment (Comments allowed). Alternatively, you can directly enter node:comment into the 'Data selector' field. If you let you let your mouse hover over `node:comment (Comments allowed)' entry in the dropdown you will see a helpful tip: Whether comments are allowed on this node: 0 = no, 1 = closed (read only), 2 = open (read/write). This helps with the next step.
Continue
If the next page isn't showing a 'Value' field, click on the 'Switch to the direct input mode' button.
Enter 2 into the 'Value' field. This sets comments to 'Open (read/write)'.

The rule just created will switch on comments when the chosen taxonomy term is present. But if that taxonomy term is later removed the comments will still be open. To turn off comments when the taxonomy term is absent, first clone the rule just made and then make a couple of small tweaks.

From the main Rules configuration page, click the ‘clone’ link for the rule you have just created, e.g. 'Enable comments when tagged blog'
Change the name of the rule, e.g. to ‘Disable comments when not tagged blog’. Save changes.
Edit the ‘List contains item’ condition.

Check the ‘Negate’ box. If the original condition succeeded, i.e. evaluated as TRUE, when the Tags field included the term ‘Blog’, this modified condition will succeed only when the Tags field does not include that term.
Save.

Edit the ‘Set a data value’ action. Replace the value 2 with 0. Save.

This second rule switch off comments when the chosen taxonomy term is absent.

Note: if a 'List contains item' gives an Error: The data type of the configured argument does not match the parameter's list requirement error, then your term reference field is set to allow only one value. You will need to delete the List contains item condition and replace it with a Data comparison condition instead. In the complementary case where Data comparison condition is used when a List contains item condition is needed, errors will be generated when the rule is run and the rule will not work.


Search api excerpt are empty in the result

First go to this path
admin/config/search/search-api/index/default_index/processors#edit-processors-highlight-settings
make sure this settings are enabled

Next i created a view Global search which has search Excerpt field.

Finally i was able to see the highlighted text word after searching

Actually this is not default search form that comes in drupal8 it is exposed form in block if you see in view exposed form setting i have enabled it.
once this is done, exposed form comes in block just place that in which ever regions you want.


How to display search query in view's results page?

Yes, ultimately all the filters send the data using HTTP methods GET/POST. If you are not using AJAX with views then HTTP method GET is used to send the data.

To display the information in header add Global:Custom Text field and add below line in it.

Showing results for $_GET[X] size and $_GET[Y] color.

Where : X - name of size field
        Y - name of color field
You will get the names from the url generated after search in address bar.


Drupal login using other subdomain user account with certain role

Are you using different databases for all sites? or the Domain Access module? https://www.drupal.org/project/domain

If you are using different databases for each site and if they are on the same server I would consider to let the sites share the users + users_roles table.
In that way all users exist on all of the sites with the same password and have the same role everywhere. You can then assign different permissions to different roles per site.


Try the views hacks module (really not the best name for a module).

Specifically see the part on the project page at https://drupal.org/project/views_hacks#views_filters_selective


Out of the box, there is no concept of sub pages or child nodes in Drupal. What you refer to is the menu structure used for navigation. A node can have a menu items linking to it and menu items can be organized hierarchically. The system was not designed to create and define relation between nodes, but only for navigation. If you look at the API, there is no simple way to retrieve the children of a menu item.

The book module included in Drupal core can be used to create a hierarchical structure for nodes. There are other options such as the relation, references and node hierarchy modules.


Best practice when testing module updates

A solution that I would very much like to test, but haven't so for, is combining a branching model like this one, not necessarily with git, with selenium automated testing. Every night, a tool like Jenkins pulls the development branch, runs drush make, drush site-install, and runs your selenium test suite.

I also remember reading an empirical study about finding bugs in software, that I unfortunately can not find a link to right now. The findings were, that no single way of finding bugs was "good enough", and that at least two separate models, such as "Test-driven", "User beta testing", "Code review", etc, were necessary to reach a high, +75%, level of found bugs, prior to release.


How to change field label name in a view programmatically

You can use hook_views_pre_render() for that.

Add this function to your template.php file:

function YOURTHEME_views_pre_render(&$view) {

  switch ($view->name) {
    case 'name_of_your_view':

      // do some logic for your label
      $label = 'My dynamic label';

      // define the label value
      $view->field['fieldname']->options['label'] = $label;
      break;
  }
}

Now, the label value will be always as the logic result. No matter whether the label is defined via Views Ui or not, it will be altered by your logic anyway.


libraries_get_path is defined in libraries.module

Make sure the Libraries API module ( e.g 7.x-2.0 ) is installed and enabled.


EntityFieldQuery for retrieve only 1 field

The code looks correct. Note that according to the field_attach_load() documentation:

  The field ID that should be loaded, instead of loading all fields, for each entity. Note that returned entities may contain data for other fields, for example if they are read from a cache.

So having other fields than field_email_per_comunicazioni does not mean the code does not work properly.


How to build route for entity without loading it?

Even in Drupal 7 https://api.drupal.org/api/drupal/includes%21common.inc/function/entity_uri/7 you needed the full blown entity for the URI to it. There's nothing new here.


Create a form in a block with a hidden field the captures the product name or information and then place the block wherever you want it.

Either store the information or just email it directly.


How do I overwrite node title for specific content type?

Every implementation of hook_preprocess_node() made from a module (or a theme) is executed after template_preprocess_node(), which contains the following code:

  $variables['node_url']  = url($uri['path'], $uri['options']);
  $variables['title']     = check_plain($node->title);
  $variables['page']      = $variables['view_mode'] == 'full' && node_is_page($node);

template_preprocess_node() is the preprocess function executed from the Node module, which is the module that defines theme_node().

The template file is then using $title for the page title.

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

  <?php endif; ?>
  <?php print render($title_suffix); ?>

If you want to change the value for title, you should change the value of $title, in your preprocess function.

The execution order of preprocess functions is explained in the documentation for theme(). In that documentation "HOOK" is a placeholder for the type of the preprocess function, e.g. "node," "html," and "page."
Between the rendering engine used for the theme, a module, and the currently set theme, the preprocess function implemented from the theme is the last one to be called. This helps if there is another module that alters the title, and you want to use the one set from the theme.

What I reported is also valid for Drupal 6.


Here's a screenshot of clean install with Content access module and Rubik admin theme:


updating database fields of custom entity

If you look at this guide, defining field definitions, it all looks right. Do you get any errors, or does it still work?

Remember to clear the cache.


Preprocess execution is not where my view is

In Drupal 8 it is possible to have preprocess functions for the theme suggestions.

So let's say if your template for the View is views-view--test-view--block-1.html.twig, you would have following preprocess functions:

THEMENAME_preprocess_views_view__test_view__block_1
THEMENAME_preprocess_views_view__test_view
THEMENAME_preprocess_views_view


Proper use of hook_menu_breadcrumb_alter()

The properties for each trail item that are documented are the following:

title: Title of the item
href: Drupal path of the item
localized_options: Options for passing into the l() function
type: A menu type constant, such as MENU_DEFAULT_LOCAL_TASK, or 0 to indicate it's not really in the menu (used for the home page item)

The code that builds the breadcrumbs is the following.

foreach ($active_trail as $parent) {
  $breadcrumb[] = l($parent['title'], $parent['href'], $parent['localized_options']);
}

The other values (type and link_path) are not used to create the breadcrumbs, but they could be used from other modules that alter the breadcrumbs. Using the default values used from menu_set_active_trail() for those properties probably causes less compatibility problems with other modules.

$trail[] = array(
  'title' => t('Home'),
  'href' => '<front>',
  'link_path' => '',
  'localized_options' => array(),
  'type' => 0,
);

  Is there a proper method (or best practice) for testing whether $item is a node and to load it?

The $item argument hook_menu_breadcrumb_alter() gets is the value returned from menu_get_item(). If you want to check it is for a node, you can use the following code.

if (isset($item['load_functions'][2]) && !empty($item['map'][3]) && $item['load_functions'][4] == 'node_load') {
  $node = $router_item['map'][5];
}
else {
  // The menu item is not for a node.
}

That is the code executed from menu_get_object() when it is called with its default arguments.

References

menu_get_active_breadcrumb()
menu_set_active_trail()


How do I connect to an external database and specify the schema to use?

You can specify a PGSQL schema using the prefix setting in settings.php

 * You can also use a reference to a schema/database as a prefix. This may be
 * useful if your Drupal installation exists in a schema that is not the default
 * or you want to access several databases from the same code base at the same
 * time.
 * Example:
 *   'prefix' => array(
 *     'default'   => 'main.',
 *     'users'     => 'shared.',
 *     'sessions'  => 'shared.',
 *     'role'      => 'shared.',
 *     'authmap'   => 'shared.',
 *   );

More info: https://api.drupal.org/api/drupal/sites%21default%21default.settings.php/7 > "View Source"

If that's not working for you, make sure the rest of the database connection details are correct. (e.g you're using 'shared.' presumably that schema also exists)


I think the problem was not specifying an id attribute for my table when I first render it, so there was nothing to replace.

This seems to work:

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $job_id=NULL) {
    $jobs = $this->_query("
      select *
      from Active_Job_List;
    ");

    $formatted_jobs = [];
    $len = count($jobs);
    for($i=0; $i<$len; $i++){
      $formatted_jobs[$jobs[$i]['Job_ID']] = $jobs[$i]['Job_Name'];
    }
    natsort($formatted_jobs);

    $form['job_id'] = [
      '#weight' => 1,
      '#title' => t('Job'),
      '#type' => 'select',
      '#options' => $formatted_jobs,
      '#ajax' => [
        'callback' => '::showFiles',
        'wrapper' => 'ajax-wrapper'
      ],
      '#required' => TRUE,
      '#default_value' => $job_id
    ];

    $form['jobfiles'] = $this->_files_table($job_id);
    $form['jobfiles']['#weight'] = 2;

    if($job_id != null){
      $form['newfile'] =  [
        '#weight' => 3,
        '#title' => t('Upload new file'),
        '#type' => 'link',
        '#url' => Url::fromRoute('JobFileUpload.UploadForm', ['job_id' => $job_id]),
        '#attributes' => [
          'id' => ['new-file']
        ]
      ];
    }

    return $form;
  }

  public function showFiles(array &$form, FormStateInterface $form_state) {
    $job_id = $form_state->getValue('job_id');
    // $form_state->setRedirectUrl(Url::fromRoute('JobFileUpload.OverviewWithJobId', ['job_id' => $job_id]));

    $table = $this->_files_table((int)$job_id);
    $link = [
      '#type' => 'markup',
      '#markup' => new FormattableMarkup('Upload a new file...', [':link' => (Url::fromRoute('JobFileUpload.UploadForm', ['job_id' => $job_id]))->toString()
      ])
    ];
    $renderer = \Drupal::service('renderer');

    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#ajax-wrapper', $renderer->render($table)));
    $response->addCommand(new HtmlCommand('#new-file', $renderer->render($link)));

    return $response;
  }


How to make Paragraph label configurable

You have a few options:

As commented, either make it a non-paragraph field
Implement some custom form alter, change the the label there
Use two different paragraph types with a different label, allow only one of the two on each node type.


I solved this by adding the view of the second box in the footer of the first box and add the php code of the third box in the footer of the second view. This way only one box is shown and with the help of the blok_wrapper css can be used to layout this template.


How do I get a date selector field in a content entity?

Your problem is that you are setting the option on the form and not the field.  The datatime field has an option, datetime_type which can be two strings 'date' or 'datetime' (see DateTimeItem), and it defaults to 'datetime'.

So, when you are creating your field, you need to update this setting.  The following should work for you:

$fields['start_date'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Start date'))
  ->setDescription(t('The date that the survey is started.'))
  ->setSetting('datetime_type', 'date')
  ->setRequired(true)
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

As a side note, when you are having problems like this, the first place to look is at the class implementing the field that you are using, and then look at the tests that cover that field.  Often, you will find the example code that you need.  In this case, you would look at DateTimeFieldTest and see what that integration test is doing.


How to set date display format for jQuery datepicker?

To change how the datepicker displays in your content entry form, go to Structure > Content types > YourType > Manage fields > YourField. Expand the section labeled, "MORE SETTINGS AND VALUES", then select the desired date format from the "Date entry options" select list.


Group search result of drupal 7 and show them in tabs

Thank you for sharing. I made some minor changes in your code because I was getting some floating search results. So I changed this part:

    $output .=  '
';
    $output .=  $value;
    $output .=  '
';

}
    $output .= '
';
    $output .= '
';

     $variables['search_results'] = $output;

To this:

$output_results .=  '
';
$output_results .=  $value;
$output_results .=  '
';

}
$output .= '
';
$output .= $output_results;
$output .= '
';

 $variables['search_results'] = $output;


You need to use function hook_preprocess_HOOK.

function themeName_preprocess_page(&$vars) {
    if (!empty($vars['node']) && arg(2) == 'edit') {
    $vars['theme_hook_suggestions'][] = 'page__node__' . $vars['node']->type .'__edit';
  }
}

This allowed me to use: page--node--[contentType]--edit.tpl.php

Clear cache.


programatically find unpublished node count in drupal

You just want to query the node table for example

here a sample function sent the content type machine name to this function will give you unpublished node count:

function get_unpublish_node_count($type){
            $db_query = db_select('node','n')
            -> fields('n',array('nid'))
            -> condition('n.status',0,'=')
            -> condition('n.type',$type,'=')
            $result = $db_query->countQuery()->execute()->fetchField();
            return $result;
}

Same function you can use this for published node count

function get_publish_node_count($type){
            $db_query = db_select('node','n')
            -> fields('n',array('nid'))
            -> condition('n.status',1,'=')
            -> condition('n.type',$type,'=')
            $result = $db_query->countQuery()->execute()->fetchField();
            return $result;
}

just change the status to "1" will give you published node count

Hope this helps :)


Migrate plugin migration_lookup : dynamic migration id

As @Hudri suggested, I've created my own process plugin (extending MigrationLookup plugin):
my_module/src/Plugin/migrate/process/CustomMigrationLookup.php

namespace Drupal\my_module\Plugin\migrate\process;

use Drupal\migrate\Plugin\migrate\process\MigrationLookup;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;

/**
 * @MigrateProcessPlugin(
 *   id = "custom_migration_lookup"
 * )
 */
class CustomMigrationLookup extends MigrationLookup {

  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    // We set the migration id based on the field configured in "migration_id_source"
    $this->configuration['migration'] = $row->getDestinationProperty($this->configuration['migration_id_source']);
    // We continue with the standard migration_lookup process
    return parent::transform($value, $migrate_executable, $row, $destination_property);
  }

}

The migration config :
process:
  pseudo_field_migration_id:
    plugin: static_map
    map:
      content_a: node_a_migration
      content_b: node_b_migration
    source: entity_type
  field_entity_reference:
    plugin: custom_migration_lookup
    migration_id_source: 'pseudo_field_migration_id'
    source: entity_id


Can Pressflow 7 be a drop-in replacement for Drupal 7?

It's not that there are problems with Pressflow 7, but that there are no significant benefits to it at this time. This is stated in the lines above your quote:

  If your project is built on Drupal 7 you might not need to use
  Pressflow at this time because the key enhancements from Pressflow 6
  were added to Drupal 7.

You could use Pressflow 7 as a replacement, but why bother if there are no advantages? (I haven't actually used Pressflow 7 because of this).


No images, content, or theme after site migration from dev server to nginx on ubuntu

Try to give more information about the files/directories.  What user/group owns the files?  You should also make sure you know what user nginx is running on.  Try these commands for debugging:

ls -l for printing details about file permissions and ownership

ps -ef to check running processes to see if any user stands out (like www-data or www, figure out which user nginx uses)

Files in sites/default/files should be rw- permissions, and directories in sites/default/files should be rwx permissions.  rw- is 6 and rwx is 7.

The file:
-rw-r--r--  1 ubuntu www-data     468 Dec 10 15:59 test.php is owned by the ubuntu user and the www-data group. The ubuntu user can access the file with read/write, and the www-data can only read the file.  If this file were in sites/default/files it would be a problem, because the webserver wouldn't have rights to remove it.


Drush 9 - Destination Argument Does Not Exist

Just for the record - in my case, given "destination" argument was coming from an outdated custom Policy command I got when I was setting up the project - https://github.com/drupal-composer/drupal-project/blob/8.x/drush/Commands/PolicyCommands.php

It should be "target" instead and the current state of https://github.com/drupal-composer/drupal-project reflects that change.


Dificulties in modifying or duplicating a view

Instead of creating multiple views, have you considered using additional displays from the base view instead? That way they can share common configuration, but you can do things like apply a contextual filter to just certain displays.


Field widget item form alter for file field

A lot of the build logic for the file field widgets is handled in #process callbacks, so some detailed structures of each individual file's form element aren't really available during hook_form_alter()s.

You might want to preprocess the individual elements with hook_preprocess_file_widget(). Something like:

/**
 * Implements hook_preprocess_file_widget().
 */
function MYMODULE_preprocess_file_widget(&$vars) {
  // Make some alterations to normal file-field widgets.
  $element = &$vars['element'];
  if (isset($element['#file']) && is_object($element['#file'])) {
    // This is an existing file... alter $element accordingly.
  }
  else {
    // This is the actual upload widget... you may want to skip this or alter
    // it in a special way.
  }
}

You could also use hook_preprocess_file_widget_multiple() to specifically target a group of files in a file field that has cardinality > 1. In this case you may need to have some iteration logic to loop through the children elements with element_children().


You should implement prepareRow() method in your migration class. Inside prepareRow() you can read both source fields and add them to an array.
I will provide an example:

public function prepareRow($row) {
  $row->text1 = array($row->text1, $row->text2);
}

Now your source field "text1" will contain both values and it can be mapped to "field_text". "text2" has to be set to DNM (do not map).


Single click function in a Drupal behaviour?

If you don't use .once() then your code will still work but - depending on whatever else happens on the page - your click() function may be attached multiple times to the same element, which is less efficient and may cause undesired effects if, as in this case, you are using a toggle function in your callback.

Because you are limiting the scope of your selector by context, multiple attachment is less likely, but you should definitely use once() if you want your code to be robust.


How to subtract the node getChangedTime from 1 year

Going under the assumption that this is Drupal 8 (based on the $node = $form_state->getFormObject()->getEntity(); line, you can do something like this:

function demo3_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'node_page_edit_form') {
    /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
    $date_formatter = \Drupal::service('date.formatter');

    $node = $form_state->getFormObject()->getEntity();
    $changed = $node->getChangedTime();
    $review = new \DateTime();
    $review->setTimestamp($changed);
    $review->modify('+1 year');

    $form['field_message'] = array(
      '#type' => 'item',
      '#title' => t('Changed date'),
      '#plain_text' => $date_formatter->format($changed, 'medium'),
    );

    $form['field_review'] = array(
      '#type' => 'item',
      '#title' => t('Review date'),
      '#plain_text' => $date_formatter->format($review->getTimestamp(), 'medium'),
    );
  }
}

Your other option is to use the timeago methods on DateFormatterInterface.


Creating a caption for images in Drupal 7 Media module

You would need to edit the output of the media tpl file. First inspect the media html output and find any unique identifying code and then do a search in the media modules folder to find this line of code in the tpl. That's how I would do it.


Updating a drush command from drush 7 to drush 8

Drush makes an attempt to never run any code associated with a module or theme unless that module or theme is enabled. This protection is often more conservative than necessary, as some Drush extensions do not exercise any code that requires a Drupal bootstrap.

None the less, Drush 8 is more rigorous than Drush 7 was. Drush 7 would search for extensions in all of the theme folders regardless of whether the corresponding themes were enabled. Drush 8, on the other hand, ignores extensions stored with disabled themes.

Include paths provided specifically via the --include option are always searched, though; Drush makes no attempt to determine if the specified path happens to correspond to a disabled theme. This is why the workaround you found works.


Setting up permissions for non-registered users

In your menu item definitions, you can specify TRUE as the access callback to make the item always accessible.

<?php
  function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_view',
      'access callback' => TRUE,
    );
    return $items;
  }

?>

See http://api.drupal.org/api/function/_menu_check_access/7

Hope this helps,
Mark


You should really check out the Console project.
https://www.drupal.org/project/console

It allows for command line creation of modules, and will generate entities for your module.

Here's a video explaining it all in 5 minutes.

https://www.youtube.com/watch?v=agcqTEr5_48

navigate to the modules directory in the drupal root in your command line tool

enter command: bin/console generate:module enter the name for your module

enter a machine name for your module hit enter for the default path

enter a description hit enter for defaults for rest of questions

enter command: bin/console generate:entity:content

enter the name of the module you just created

enter a class name for the Entity you are creating


The issue is the way the google analytics module tracks clicks.  It adds mousedown, keyup, and touchstart events to the body and tries to match the clicked position the the closest anchor.  When it encounters a click on an SVG element it gets confused and is not able to properly match the closest anchor.

There are a couple options to remedy this:

Using :after on your anchors to create a block that covers up the SVG elements.
Using pointer-events: none on all SVG elements inside your anchor.
Turn off click tracking in your Google Analytics settings.
Unbind click tracking on your map page only with something like $('body.mymappage').unbind()
Manually patch the GA module:

Change the line (googleanalytics.js):

$(event.target).closest("a,area").each(function() {

to:

$(event.target).closest("a,area").not(".svg-anchor").each(function() {

The first 2 options are documented here, and a codepen example fix is here.


Show required user profile fields after the account is verified during first login

Use this module: https://www.drupal.org/project/required_by_role
In rules you can add rule "After login user" -> Do: redirect to "profile edit"

Or add rule if user view content -> redirect to "profile edit" and show status message "required fields need to be filled"


Is there a module that simply adds an 'add more' AJAX CCK field to a node form?

You can set any field to allow more than one value on the same node. But if you need some kind of a group of fields, which you want to add dynamically, then I would suggest you to have a look at the Field Group module.


Your best option is the Views Module:

You need Views if
You like the default front page view, but you find you want to sort it
differently.
You like the default taxonomy/term view, but you find you
want to sort it differently; for example, alphabetically.
You use /tracker, but you want to restrict it to posts of a certain type.
You like the idea of the 'article' module, but it doesn't display articles
the way you like.
You want a way to display a block with the 5 most
recent posts of some particular type. You want to provide 'unread
forum posts'.
You want a monthly archive similar to the typical
Movable Type/Wordpress archives that displays a link to the in the
form of "Month, YYYY (X)" where X is the number of posts that month,
and displays them in a block. The links lead to a simple list of posts
for that month. Views can do a lot more than that,
but those are some of the obvious uses of Views.

create a new view as a Page with Fields
add whichever fields you want displayed
assign that page address as the front page under /admin/config/system/site-information


For me the following hack worked:

Edit includes/cache.inc. Let function cache_get() return FALSE.
Run drush cc all.
Revert the hack in includes/cache.inc.

I am not saying this is the best solution. But it did work for me, on a dev system. I am not sure I would recommend this on a production system.

Here is the hack:

 function cache_get($cid, $bin = 'cache') {
+  return FALSE;
+  # return _cache_get_object($bin)->get($cid);
-  return _cache_get_object($bin)->get($cid);
 }


How can i use MATCH and AGAINST with db_select?

Adding an expression should work:

 $query = db_select('foo');
 ...
 $expression = 'MATCH(field1,field2) AGAINST (:search IN BOOLEAN MODE)';
 $query->addExpression($expression, 'Relevance', [':search' => '$s']);
 ...

See SelectQuery::addExpression for more info.


Should I be using node_load() rather than building my own queries with db_select()?

Technically, yes, writing your own db_query() statements will return the data faster and with less overhead. However, it is not really the "Drupal way" to do things.

node_load() provides a 'static' cache; in other words, if you load the same node twice in one page request, it will only hit the DB once.

What you are really missing out on by not using node_load() is all the API hooks and third-party module integration. If you need a CCK field, node_load() gets all that data for you, where as a manual query would require a lot of joins.

As you note, there is a lot of extra processing/loading going on that you may not need at the given moment. If you don't need the data, it won't technically hurt you not to have it. It is really up to you if you want to go this route.

The biggest reason IMO for using node_load() even though you might not need the extra data is just for the purpose of standardization. You won't have to worry about what pieces of data you have at a certain point. You will have a fully loaded node and will have more options for adjusting the data as necessary through hook_nodeapi(). Other developers looking at your code will have an easier time understanding what they are working with. Also, 6 months down the road when you go to add a new feature/display field you wont have to adjust your queries.

node_load is definitely a resource hog, but i have found it better to use in my experience.  Drupal 7 greatly improves the situation by providing node_load_multiple() which, as its name implies, reduces the number of queries when loading multiple nodes.


Get an error message "invalid file extension"

When you create the field file, you need to definy the extention.
You have already created the field but you can always modify it.
Go on your content type, edit the field file adding pdf on "Allowed file extensions *"

You can add all the extensions you want. Separate extensions with a space or comma and do not include the leading dot.


To avoid hacking core, this code put in a custom module accomplishes the exact same thing as the solution by Psykoral/Clive:

//Implements hook_node_view_alter()
function mymodule_node_view_alter(&$build) {
  if(isset($build['#node'])) {
    $node = $build['#node'];
    if(!empty($node->nid)) {
      $build['#contextual_links']['node'] = array('node', array($node->nid));
    }
  }
}


Getting the inverse of drupal_realpath (Drupal 7)

It's not pretty but this will reverse engineer such a path quite reliably:

$old_path = '/Applications/MAMP/htdocs/drupal/sites/default/files/my_file.png';

$doc_root = $_SERVER['DOCUMENT_ROOT'] . '/';

$public_file_path = variable_get('file_public_path', 'sites/default/files') . '/';

$replace = array($doc_root, $public_file_path);

$new_path = 'public://' . str_replace($replace, '', $old_path);


Update image in image widget (automatically upload?) on another ajax reference field's autocompleteclose event

No that isn't possible. You can't automate completion of a file input field, it would be a massive security hole (I think browser plugins for chrome/Firefox can do it, but they run in a different security context to website scripts anyway)

If it were possible, anyone with a website could steal any file from any visitor's computer they fancied.


Drupal forms should be called using the drupal_get_form() method, even from menu callbacks. Your menu item needs to look like this:

$items['myform/data_entry_form'] = array(
  'type' => MENU_CALLBACK,
  'access arguments' => array('access content'),
  'page callback' => 'drupal_get_form',
  'page arguments' => array('myform_data_entry_form')
);

return $items;

Make sure you clear Drupal's caches each time you make a change in hook_menu(), otherwise it won't get picked up.


I've been through a similar situation and I resolved it depending on the feeds module.

You need to use the following patch to allow the address field to be recognized by the feeds module
https://www.drupal.org/project/address/issues/2882589

This is might not be what you're looking for at this stage but I thought this might help.


How to use default field_image if value is not provided?

Seems the default image procedure as it is now doesn't store a file ID or something more useful in that image field. Means the image field doesn't get populated properly.

What I'd try is to create a custom module that adds a config page with a form and a '#type' => 'file_managed'field. The resulting file ID on upload now becomes variable via \Drupal::configFactory()->getEditable()->set() (and together with the right config/install and settings YML files).

Then I'd alter the node form via hook_form_BASE_FORM_ID_alter (see comments) and add a custom validate and/or submit function. Maybe just an element validate callback on the image field. And then check on submit if this field is empty, and if so then retrieve the file ID from the config page via \Drupal::config()->get(), load the file and save it into the image field (maybe the file ID is just enough).

Now the image field should be populated properly and everything else should work as expected.

Proof of Concept

OK I just tried what I wrote above and it's working quite fine. Except I didn't use the node form but hook_entity_presave instead to check if the image field is empty before setting the file ID retrieved from the settings value of the uploaded file on said config page.

Download or clone https://gitlab.com/leymannx/tdi
into /modules/custom.
Enable the module.
Go to /admin/config/media/tdi and upload a default image, save.
Now in your IDE or code editor open /modules/custom/tdi/tdi.module and

update the bundle if ($entity->bundle() == 'XX-YOUR-NODE-TYPE-HERE-XX') {
and the field name $entity->get('field_XX-YOUR-FIELD-NAME-HERE-XX')->setValue([['target_id' => $fid]]);

Save the module file.
Go to a node with an empty image field, edit and resave it, done.

On every node creation or update this module will check if the image field is empty and add a real managed image with a real file ID then. Now the metatag module should work just fine. If updating all nodes manually is too fiddly I'd recommend you let some code do that instead :)

I'm thinking about extending this approach to let admins choose content types and field names this default image should be set automatically. Maybe tomorrow ;)

Alternatively

If this doesn't work or if it's just too messy, the next thing I'd try is to hook into hook_page_attachments_alter same as schema_metatag_page_attachments_alter does to actually attach its values to the HTML head, and try to alter the values there. Which might become messy as well, depending on what methods you have available when you get there or if all you get is just a string to be manipulated quick and dirty.


Disable a field for input, without deleting it (to not lose old data)

You can use the Field Permissions module to remove permissions for users to access the field.


Get Thumbnail Image URL for Video in Views

You are looking for the Image URL Formatter module.


It looks like the module Webform HTML Textarea might do what you're wanting. It allows you to use the site's input methods (Filtered text, plain text, etc.). So you could make a limited one for your users with only the options you need (bold, italic, underline, etc.).


You have to call the same callback issued from node/%node menu i.e. node_page_view :

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

  $items['mymodule/info'] = array(
    'title' => t('My module'),
    'description' => t('My module description'),
    'page callback' => 'node_7',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function node_7(){

include_once(drupal_get_path('module','node') . '/node.pages.inc');

return node_page_view(node_load('7'));

}


"Responsive", as mentioned in your comment, is indeed the buzzword. On a small scale, I have had success using Sky to create a mobile friendly site.


The edit links where fixed in i18n 7.x-1.6. When I crated this issue I was using 7.x-1.5.

http://drupal.org/node/1649596


How to resolve my error in bootstrap.inc?

The file

  D:\xampp\htdocs\kaya/sites/all/modules/commerce_invoice_receipt/commerce_invoice_receipt.admin.inc

Is missing; the Commerce Invoice Receipt module is installed on your site, so the file needs to exist.

If you've lost the file(s) somehow, just download the module again and put it back in place.

If you've removed it on purpose, but without uninstalling the module, follow the above first, then disable and uninstall it. Then you can remove the files safely.


/admin/modules and Views Edit pages take forever to load

I found more information on this and have fixed it.

I guess that when Drupal has enabled modules that are missing from the filesystem (this happened as we're using Capistrano to deploy and I didn't sync the two sites correctly), it recursively keeps calling file_scan_directory() trying to find the missing modules, and that causes the site to timeout.

References:

Avoid re-scanning module directory when multiple modules are missing

Drupal 7 speed issue: file_scan_directory called > 1000 times per page load

Used XHProf to see what the call stack looked like over the course of loading /admin/modules and found over 5,000,000 function calls. By contrast, any other page had about 30,000 ~ 50,000 function calls.


programmatically add line item of commerce_discount type to order

Don't reinvent the wheel, here. Discounts provides functions for apply discounts to orders:

// Pass in an $order or $product that has been entity_metadata_wrapper()ed.
// And pass in a discount name.
commerce_discount_fixed_amount(EntityDrupalWrapper $wrapper, $discount_name);

// Same thing, but a percentage.
commerce_discount_percentage(EntityDrupalWrapper $wrapper, $discount_name);

If you must reinvent the wheel, use these functions as examples to guide what you are doing.


Non-autocomplete Widget for Term Reference Fields on Content Type

The code for the @2pha suggestion:

function MODULENAME_form_CONTENTTYPE_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_name']['#ajax'] = FALSE;
}


How to show the status of a referenced webform in view of nodes?

Since the webform is added as a reference on the node, you have to add a relationship in views, in order to get the webform's fields.

Go to relationships and add the webform reference, then the status field should be available as a field.


Force a page to be rendered in admin theme

You can add the _admin_route option to a route:

aggregator.feed_add:
  path: '/aggregator/sources/add'
  defaults:
    _controller: '\Drupal\aggregator\Controller\AggregatorController::feedAdd'
    _title: 'Add feed'
  requirements:
    _permission: 'administer news feeds'
  options:
    _admin_route: TRUE

You can also implement your own negotiator (See \Drupal\user\Theme\AdminNegotiator) or add that option to routes dynamically in a request subscriber.


You certainly can.

You need Entity and Entity Token (comes with Entity module) modules.

Clear cache after enabling them. The referencing node info will be available to you.

For the 'referencing' functionality, I use Entity Reference instead of Node Reference which will most probably be deprecated in the near future in favor of Entity Reference.    (but I remember node reference info is also available in Pathauto pattern, you may try yourself)


You can use EntityFieldQuery,

Here is the sample code,

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('vid', 1) // change 2 to any vocabulary ID
  ->fieldCondition('field_test', 'value', 'test');
$terms = $query->execute();

First param to fieldCondition is the field name, second one will be the column name for example for text fields column name is value and for term reference field tid, then the final one is to specify the value. Hope this helps.


How to generate a resume after an applicant submitted an online resume?

I would create a profile type using Profile2 module and call it something like 'Resume'. So that every user can create a Resume profile for themselves.

Then I would install Print module and enable Print PDF and set it to show up on Resume profile pages.

You must play with the permissions so that only the owner of the profile can access the profile page and the PDF version. You may have to write some custom code to make PDF version accessible only once. You may achieve this writing an access callback function for the PDF path.


How do I create a role programmatically?

The problem is in the data array change name by label:

$role = \Drupal\user\Entity\Role::create(array('id' => 'client', 'label' => 'Client'));
$role->save();

Or you can use:

//your data array
$data = array('id' => 'client', 'label' => 'Client');
//creating your role
$role = \Drupal\user\Entity\Role::create($data);
//saving your role
$role->save();


Exposed proximity filter in geofield required, but still gives result

Hope you are using Better exposed filter module and configured as this image.