How do I use non-admin theme for page containing node form?

Well, the issue was related to the bug in metatag module, it was in version 8.x-1.0-beta11.

It caused break of my routes when they ended with /add. It was trying to handle prefix of path as entity type, so my routes worked fine only if I had _node_operation_route: TRUE in route options. But if this option is set _admin_route: TRUE is added by core.

I updated metatag module to the latest version (8.x-1.0 currently) and found they've added check for existing entity type, so I'm not forced to use _node_operation_route: TRUE anymore and I'm able to output custom routes in a default site theme.


The problem was fixed by my collegue when he MySQL. Unfortunately, I didn't find any errors displayed on screen or in the logs, so I'm not sure what happened.


Display the flag link only for the node author

You may use hook_flag_access(), as in the following code.

 function crystal_qa_flag_access($flag, $entity_id, $action, $account) {
   // Only the author of the question has right to use flag "Accepeted" on answers.
   if (($flag->name == 'accepted') && ($flag->content_type == 'node')  && ($node = node_load($entity_id))) {
     if ($node->type=='answer') {
       // The content type machine name must be answer.
       $question_nid = $node->field_answer['und']['0']['target_id'];
       $question = node_load($question_nid);
       return ($question->uid == $account->uid);
     }
   }
 }


Getting all the values from a entity reference field (Drupal 8)

You have to loop over the field items:

{% for item in node.field_reference %}
  {{ item.entity.label }}
{% endfor %}


How to hide all nodes of a particular content type?

Try the Rabbit Hole module:

Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.
Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.


How can I break into my own Drupal site?

If you're using Linux:

Install drush if you haven't already
Go to /install_directory/sites/mysite
Type sudo drush uli
Copy the link to your browser

Drush is extremely useful for many things.  The above will log you in as user 1, after which you can reset your password in the usual way.


Getting redirected to the referenced node instead of the created node after node save

As a workaround i created a rule (rules module) where i redirected the user upon saving new content.
In my action i used this piece of code:

global $user;
$uid = $user->uid;
$result = db_query ( "SELECT * FROM {og_membership}
WHERE etid = :uid
and entity_type = 'user'
order by gid DESC", array (':uid' => $uid ) );

Then i used this for my page redirect:

<?php print "node/".$_SESSION['ses_user_group_gid'];  ?>


Change 'Administration theme' not working - still shows current theme for administrative tasks

Toolbar - Use the Administrative toolbar is a role permission. Check there if you are having the same problem to make sure it's checked for the role you would like to be able to access the toolbar at the top of the page.


How can I use the OpenLayers module to draw a route between nodes?

OSM Route looks like it will do exactly what you need.


Use an IDE to open your site and search into all your files.

When you find one exit(), comment it and try to use Drush again. Do it until you find the exit() that block Drush.


Drush installed and running; No Drupal site found even with uri specified

Please double check that all below points are addressed.

You're running drush in Drupal root folder or folder containing settings.php file.
The mysql command exists (and it's in your PATH).

Please note that the database command depends on your database driver set in your settings file (e.g. sqlcmd for SQL Server; for details check different classes in Drush's /src/Sql).

If the command is missing when running in any folder, make sure path to its binary file is added into your PATH system variable.
Your PHP has PDO extension enabled (check by: php -m | grep pdo or drush sqlc).
Your PHP has database extension enabled (e.g. mysqli) (check by: php -m | grep mysql).

To investigate what's exactly wrong, run drush with -v (verbose) and -d (debug) flags, e.g.

drush -vd status
drush -vd ev "echo 123"
drush -vd cc all

and check for any errors.

  mysql extension for PHP PDO is not installed. Check your php.ini to see how you can enable it.

Install database extension (e.g. mysqli) (as per above 4th point).

For MAMP, see: Drush does not work on my Mac

MAMP

Since you're using MAMP, make also sure you running the right version of php binary (check by which php) and it should point to /Applications/MAMP/bin/php/php5.X.X/bin/php. If not, please add the path into your PATH in your rc files (e.g. ~/.bashrc):

# For MAMP (OSX)
PHP_VER="5.6.10" # Or: 5.4.19/5.5.3 (check by: $ ls /Applications/MAMP/bin/php/php*)
export PATH="$PATH:/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php/php$PHP_VER/bin:/Developer/usr/bin"

XAMPP

For XAMPP for Windows, similar thing, add your C:\xampp\mysql\bin into your environment variable PATH.

Debugging

If your drush command fails for some reason, here are the suggested steps to debug drush (shell commands).

Install and enable PHP xdebug extension. Verify by php71 -i | grep xdebug.
Verify Drupal root, Settings File and Database are present in drush status.
Generate trace file:

drush ev "xdebug_start_trace(); drush_drupal_cache_clear_all(); echo xdebug_get_tracefile_name(); xdebug_stop_trace();"

or:

drush ev "xdebug_start_trace(); print_r(_core_site_status_table()); echo xdebug_get_tracefile_name(); xdebug_stop_trace();"

If xdebug is enabled for different PHP version, specify with DRUSH_PHP=/path/to/php.

If successful, trace output file should be printed at the end, so take a note of it.
Now open and check the trace file.
To test or compare drush output with clean Drupal, you can install new Drupal in empty folder by:

drush -y qd --no-server --core=drupal-8
cd quick-drupal-*/drupal*
drush status


Restricting view to content associated with user profile

What you're wanting is a contextual filter for your view. Create a node view with a block display and in the Advanced section under Contextual Filter click the Add button.

From there you can add Content: Author uid which will tell the view to filter by author UID. On the popup modal, under the WHEN THE FILTER IS NOT.... fieldset, select Provide default value with Type of Raw value from URL and Path component of 2. This essentially tells the view to pull the UID from Drupal's internal path (i.e. the XXX in /user/XXX when viewing a user page).

After saving the view, you should be able to place it your region to display against user profile pages.


How can I limit a views_pre_render() to a specific display of a view?

Like so:

/**
 * Implements hook_views_pre_render().
 */
function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'VIEWNAME' && $view->current_display == 'DISPLAY_NAME') {
    // Do your thing here.
  }
}


Re-write output on different images on Views Slideshow

Image Field Caption

Adds an extra text area for captions on image fields.
Similar to the alt and title text fields available with an image
field, the caption text area can be used to enter text or html
descriptions of an image.

Has views integration.


Dynamic data forms and reports from non-Drupal databases

Consider the Forena module, not many people know about it, which is why I wanted to mention it here.

Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Various DBMSs are supported, such as Oracle, MS Sql, Postgress, SQLite, MySQL, any PDO compliant DBMS ... And there are quite some reasons for considering Forena.

Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links.

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


How to export content from dev environment for deployment to production environment?

I haven't done it myself but a colleague of mine had to do this last week. It's just exporting and importing the database. He used HeidiSQL with this link: https://support.appliedi.net/kb/a1034/how-to-import-and-export-a-mysql-database-using-heidisql.aspx


IS there a replacement for 'taxonomy_node_get_terms_by_vocabulary' in Drupal 7?

I don't think an EntityFieldQuery would work in this case as you'd be trying to reference two types of entity in the same query (which cannot be done currently). The easiest way would be to build up the query yourself:

function taxonomy_node_get_terms_by_vocabulary($node, $vid) {
  $terms = &drupal_static(__FUNCTION__, array());

  if (!isset($terms[$vid])) {
    $terms[$vid] = array();
  }

  if (!isset($terms[$vid][$nid])) {
    $query = db_select('taxonomy_term_data', 'td')
      ->fields('td', array('tid'))
      ->condition('td.vid', $vid)
      ->condition('i.nid', $node->nid)
      ->orderBy('td.weight');

    $query->join('taxonomy_index', 'i', 'i.tid = td.tid');

    $terms[$vid][$nid] = taxonomy_term_load_multiple($query->execute()->fetchCol());
  }

  return $terms[$vid][$nid];
}


How to Display "Tabbed" content from Views in Panel / Pane in Node Template

In the end, I used the "Panel Tabs" module. It is available in dev version, which gave me pause, but it works well on the main platforms (Chrome / iE / Firefox); I haven't played around on Safari.

With a little css, this will be a good working solution, but I would be interested to know if others have a more standard approach.

Thanks,
keb


Count multivalue image field values in views-view-fields.html.twig

Your D7 PHP would translate into D8 Twig like this:
{% set node = row._entity %}
{{ node.field_gallery_photo.getvalue | length }}


How to add / update a field collection without updating parent node/entity?

You can make use of the Entity API

example will be

<?php
// Implements hook_entity_update().
function qmlc_mod_entity_update($entity, $type) {
  if ($type == 'node' && $entity->type == 'event') {
    $link_title = $entity->title;
    $link_url = entity_uri('node', $entity);
    $language = $entity->language;

    foreach ($entity->field_event_images[$language] as $event_images) {
      // Load field collection item.
      $field_collection = field_collection_field_get_entity($event_images);

      $num_of_images = count($field_collection->field_image[$language]);
      for ($i = 0; $i < $num_of_images; $i++) {
        $field_collection->field_image_link[$language][$i]['title'] = $link_title;
        $field_collection->field_image_link[$language][$i]['url'] = $link_url['path'];
        $field_collection->field_image_link[$language][$i]['attributes']= array();
      }

      // Save field collection item. Use TRUE since you are updating a field collection item which is already linked with a node.
      $field_collection->save(TRUE);
    }
  }
}
?>

References

Programmatically create and update field collection with Entity API
Update field collection programmatically


Adjust number of posts that appear on front page

On Drupal 7: mysite.com/admin/config/system/site-information

Set the Number of posts on front page option to your liking.


Remove permission for anonymous users to edit views from yoursitesname.com/admin/people/permissions

It kind of a long page, so try "ctrl+f" and there type "administer Views" and uncheck the right permission.

If it's not helping, try using another Newsletter module (It's maybe a bug since there is no logical reason to give to email subscribers edit your views, of course).

Please update in comment what worked for you.


Exporting and importing a view from a custom module

Content types and Views are 2 different things. It's your job as a module developer to keep the two in sync over time.

Some modules can help with this such as the Features module, if you dont want to track all this by hand every time.


How get views advanced dynamic URL contextual filter to work with full taxonomy path?

You must use 2 contextual filters

First one is: Contextual filter: Content: Has taxonomy term ID depth modifier

Second one is: Contextual filter: Content: Has taxonomy term ID depth modifier with the same criteria you did.

I put the view path to be the vocabulary name and tested contextual filters like:
//Hierarichay
      tag1
        tag2
        tag2

//Urls
    tag1/tag2
    tag1/tag3

The views gets results for the child tags every time {2, 3}.
If you didn't use the first filter it will consider the parent as argument.
Hope it solve your problem.


How to create a Notification system in D7?

In the Drupal community, "notifications" are usually referring to email notifications sent to users.

Messages sent to users to indicate "likes", etc. are usually called "messages". So you should probably search for "messages" and "messaging" (instead of "notifications") to locate stuff about this type of user interaction.

One of the most popular Drupal modules for messages is HeartBeat:

  Heartbeat displays user activity on a website. This module is an API to log activity. The logged data contains message structures, attributes and variables. Once the activity messages exist in the database, they will be parsed and build into activity streams.

However, the maintainer of Heatbeat has recently announced:

  This project will be deprecated. The future would be in the module Message. It's much smaller and it cannot be compared to heartbeat when it comes to features. However the possibilities as API would be the same.

At the time of writing, Message is an API that you can use to build the required flagging and messaging by combining it with other modules in the message stack. As for social messaging functions, you need to  add those. The Heartbeat API already has all the necessary functionality built-in.  Today, it will take much less effort to get something working with Heartbeat than with Message, but maybe Message is still a better option than putting efforts into working with a module about to be depreciated,


Deciding between (CCK) Fields and Taxonomy for a list of options. Pros and cons?

This is my personal opinion:

Use taxonomy terms is you might need to change them later, re-arrange them, add or remove (yes remove, bad, but ok), share them between content types and have a page per each listing all the content that have it and also provide an RSS feed of the same.

Use options list or CKK option list is you know for sure the options will never change, if you need to have a key-value configuration if you want to share them between content types, but don't want to have listing pages of the content that have it. Also fields can have grain level permissions and don't generate RSS feeds.


Can I use same (machine) name for taxonomy and content type?

Technically you can have same name for taxonomy and content type as the underlying machine name is not the same and there is no confict.

Practically it might not be a good idea as it might confuse the end users but  it depends on the problem you are trying to solve.

So based on your description staff category might be a better name for your category.


If you're able to use a flex container for your divs all in the same div, you might try using the order property in a media query for smaller screens. It lets you select the order of elements. I've done a fiddle here.

Here's the CSS I used.

.row1 {
  display: flex;
  flex-wrap: wrap;
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
}
@media (max-width: 767px) {
  #col1 {order: 1;}
  #col2 {order: 2;}
  #col3 {order: 4;}
  #col4 {order: 3;}
}


You'll probably have to save your Excel file to CSV format to be able to import more easily. Two options:

Node Import: You can certainly import CSVs with this, and I've used it successfully for huge spreadsheets before -- it's powerful, helpful and quite easy.
Feeds: Much more complex to get going than Node Import, but Feeds can in theory do everything you want and much more. Can also update existing nodes.

Either of these will allow you to import CSV data (exported from your Excel document) to nodes and their CCK fields.


How can I modify body class based on non-taxonomy node data?

You could do this in your theme's template.php. Something like this:

function mytheme_preprocess_html(&$vars) {

  // Load node
  $node = menu_get_object();
  if ($node) {

    // Wrap to fetch field values easily
    $wrapper = entity_metadata_wrapper('node', $node);

    // Check image reference fields and add body class
    if (
      $wrapper->field_featured_image->raw() ||
      $wrapper->field_image_gallery->raw()
    ) {
      $vars['classes_array'][] = 'my-class';
    }
  }
}


Render content type via Form Block module using module_invoke

You can print a Block which is generated by a module like this.

$block = module_invoke(<module name>, 'block', 'view', <block id>);
print $block['content'];

User created block

$block = module_invoke('block', 'block', 'view', <block id>);

example:

$block = module_invoke('block', 'block', 'view', 20);
print $block['content'];

In Your cas, since the forms are in blocks you can simply manage them via exmple.com/admin/structure/block path :)


which hook to change the node order in a view?

You can use View's prerender hook to modify the view's results anyway you want.

For example,

function YOURMODULE_views_pre_render(&$view) {

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

      // modify/sort the $view->result array to your heart's content here
      // for example, reverse it...
      $view->result=array_reverse($view->result);

   }

 }

Basically $view->result is an array of row results, so, just go through it and grab the rows you want first, then follow that up with the remaining rows.

ADDITION:

I created a quick view and did the above reversing and it certainly reversed the order so I am not sure what you are doing ever so slightly wrong to not see similar behavior on your site.


How do I get machine name by entity type and its ID?

To get the type and id of a given entity, you can do:

$type = $entity->bundle();
$id = $entity->id();

Some entities, like Node, provide wrapper methods to return the bundle:

$type = $node->getType();

But Block doesn't. So if it is Block that you are after:

$block = \Drupal\block_content\Entity\BlockContent::load(2);
$type = $block->bundle();
$id = $block->id();


How can I hide the Organic Groups Audience selection?

You can set #access to FALSE to hide elements like this:

/**
* Implements hook_form_alter()
**/

function yourModule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'yourFormId':
      // We should remove the group check box from users, Its always going to be
      // checked for project content type.
      $form['group_group']['#access'] = FALSE;
      $form['group_access']['#access'] = FALSE;
      break;
    }
}

Above I removed the check box that says "group" and group audience.


How to create a view of nodes of which a user is a member?

Organic Groups provises a default view for this called "OG User Groups". You can use that as a base and adapt it accordingly.


Right way of data organasing and structuring

If your categories are pre-defined and won't change then I think your solution of using blocks regions and block visibility settings may be the best. If you need more complex visibility settings the Context module should be able to help.


drupal variables custom module and views

in your drupal_add_js, you are setting 1 variable many times. (Drupal.settings.myModule.nid). So the last one will be what this is set to.
You could add these nids to an array in Drupal.settings.myModule but then you would still need a reference from anchor in the views row that maps to the appropriate array index in your Drupal.settings.myModule array.

I think the best / easiest way to get what you want would be to set a data attribute in your views anchor using a token of the current rows nid.
Also, set it up as a class instead of an id, so you don't have the same id multiple times.
eg.

<a class="nid-button" data-nid="[node:nid]" href="#"Testing!!!

Then in your javascript you would just need to use this data attribute.

(function ($) {
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {

      jQuery(".nid-button", context).bind('click', function(e) {
        alert($(this).data('nid'));
      });
    }
  };
}(jQuery));

Doing it this way you don't even need to set any settings variables, instead it is saved on the anchor itself.


The page request for /admin/structure/block only returns part of the html and doesn't render it

I got it working.  This is what I did: I restarted Windows.


View of all users and their relationship(s) with the current one

A contextual filter does not limit the results, it only adds additional input to the view based on certain situations.

It may be a problem with the relationship.

Please check that Require this relationship is not ticked. If  it is then by its description "Enable to hide items that do not contain this relationship".

If you just add the relationship but not require it, a field taken from the relationship will only display as a blank space in your rendered view.

Hope this helps. I had the same problem before.

Update 2014/06/20

I'm assuming the view displays users.

Contextual Filters

add User:Uid -- When the filter value is NOT in the url, provide a default value -- User ID from logged in user.

This filter will set it to display based on the current user.

Relationships

User relationships: Requester user -> use the contextual filter on this

You'll have to play around with this as I'm not sure.

Sort Criteria

UID ascending

Fields

UID: (this will display all the user IDs)
(check first after adding this that ALL users are displayed.)
Relationship Type
UID: (use the relationship)

Try adding the first field first then adding all the contextual filter, relationship stuff. It has to display ALL the users.


I think I got it.

Install the Entity Reference module
Go to view and add a relationship in the advanced section
Search for your paragraph embed field and set the identifier as anything as you want
Add your paragraph fields by searching for the fields in the paragraph bundle
Click save and done!


You can perform most of the mass updates in Admin > Content page.

If you require any advanced actions, sorting, filtering, I'd suggest you use Views and Views Bulk Operations modules.


Can Webforms include the URL they were submitted from in their emails?

You can achieve this by using the %server token as the value of the hidden field. To be more precise http://%server[SERVER_NAME]%server[REQUEST_URI] should get you the full url (path alias is also preserved). For a complete list of options that can be used with the %server token check out the manual.

UPDATE:

The %server token only works for authenticated users since Webform version 2.8 due to potential security/privacy issues with some values. Since you only need the url in e-mails a better solution should actually be to put a appropriately themed version of <?php print url($_GET['q'], array('absolute' => TRUE)); ?> inside your copy of webform-mail.tpl.php file (or webform-mail-[node id here].tpl.php).


What operators and functions can I use in a Views "Global: Math expression" field?

Views Math expression fields use a custom expression parser in the Chaos Tool Suite (ctools) module. The code for this is contained in ctools/includes/math-expr.inc.

As of mid-July 2012, the built-in functions are:

'sin','sinh','arcsin','asin','arcsinh','asinh',
'cos','cosh','arccos','acos','arccosh','acosh',
'tan','tanh','arctan','atan','arctanh','atanh',
'pow', 'exp',
'sqrt','abs','ln','log',
'time', 'ceil', 'floor', 'min', 'max', 'round'

Most of these are PHP's own math functions. The trigonometric functions beginning with "arc" are aliases to the ones beginning with "a". "ln" is an alias for "log".

The built-in operators are + - * / ^

The first four act just as they do in PHP. The fifth is the exponent operator; x ^ y is the same as pow(x,y).

You can create your own functions using this syntax, and such functions can use more than one variable. You can use this to create your own modulo function:

mod(x,y) = x - (floor(x/y) * y);

(Beware: The above function does not work with negative numbers.)


How to resist anonymous user to access module internal files? eg. path starts from \Drupal\module\mymodule\files

If I've understood your requirement correctly, you've some files other than normal Drupal files, like csv, txt which should not be accessible to Anonymous user.

This should be done at .htaccess level or you can give a try to private file system in Drupal Core. Check the ans given to "how to restrict file access to specific user roles" for more details on Private File system. The question is related to Drupal 7 because of which contributed modules will not be available for Drupal 8. But you can check configuration options mentioned for Drupal 8 Core.


How to load a taxonomy term (or entity) by field value?

As specified in the EntityFieldQuery documentation. It is not possible to query across multiple entity types. It is no possible to query all the terms with a specific field value as this would require querying both vocabulary->vid and field_id->value.

To load a taxonomy term by field value is possible to get all the entities that have that value:

  $query->entityCondition('entity_type', 'taxonomy_term')
    ->fieldCondition('field_id', 'value', $IDtoFind, '=');

Using ->fieldCondition('field_id', 'value', $IDtoFind, '=') and ->propertyCondition('vid', $section_vocab->vid) in the same query would produce an empty result.

Solution

For the code in the question this would work, based on that field_id is used only one vocabulary and it value is unique.

<?php
// Get taxonomy term by field value
$section_vocab = taxonomy_vocabulary_machine_name_load('section');

$sectionID = NULL;

if($section_vocab) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'taxonomy_term')
    ->fieldCondition('field_id', 'value', $IDtoFind, '=');
  $result = $query->execute();

  if (!empty($result['taxonomy_term'])) {
    // Set the internal pointer of an array to its first element
    reset($result['taxonomy_term']);
    // Get the key value for the first item
    $termID = key($result['taxonomy_term']);

  }
}


You can ready the directory using read() function and drupal_realpath('public://') will give you the actual path to the public files folder.

$path = drupal_realpath('public://');
$dirs = array();
// directory handle
$dir = dir($path);

while (false !== ($entry = $dir->read())) {
    if ($entry != '.' && $entry != '..') {
       if (is_dir($path . '/' .$entry)) {
            $dirs[] = $entry;
       }
    }
}

echo '<pre>';print_r($dirs);echo '</pre>';


If it is node form you could use Form Block. It will create form in block and you could add that in content panes.

  Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks. This is particularly useful for
  including forms on panels.


Add a class to a image for a specific view

If your view is outputting fields (& not a teaser) you can easily do it in the views UI.

Edit your view
Click on the image field
STYLE SETTINGS > Customize field HTML > Create a CSS class
Save

Now your image field should have a class:


I figured out how to make nginx do the logging in a rudimentary way. I just added the following after my fastcgi_pass directive.

log_format cache '$time_local $remote_addr $request_uri $sent_http_x_drupal_cache';
access_log /var/log/nginx/cache.log cache;

I'm not going to mark this as answered, because there are some problems with this solution:

Doesn't exclude pages that don't have the X-Drupal-Cache header set (logged-in users)
Doesn't exclude IPs I don't want logged (mine, for example)

For now I'll just deal with those issues when I parse the log file to create my stats, but if someone has a way to exclude them from the log then that would be preferable.


Advice needed on approaching to Drupal 6 and jQuery Mobile

I personally don't recommend splitting the project in 2 sites but rather in 2 themes. If the project is slightly different (I assume you however use the same database) then try to customized it via theme (and theme functions).

I suggest you use the Omega/Fusion Theme which are responsive themes.
A responsive theme doesn't need a special redirection.

However if you need more customization in additional install Mobile Tools Module.

Then create a domain called m.domain.com in additional to your site domain.com and set inside the Mobile Tools Module based on a agent to switch to the theme needed.

There's indeed no need to install Drupal again.
You should ask your host to treat the m.domain.com as an alias for domain.com. That way it points to the same Drupal installation and the theme switch can take place.

If you don't have a mobile to test install Firefox addon: https://addons.mozilla.org/en-US/firefox/addon/user-agent-switcher/


How do I link an image field to an pdf file

Hope this will help you,

In Drupal 7 you can use VIEWS Rewrite results to link an IMAGE to a PDF file.

Steps:

In PDF field, exclude it and change the format to "URL of file"

Go to your VIEW -> Image field and under Link image to select NOTHING
And then go to Rewrite results and check Output this field as a
link and give the path of the PDF file.

You can also use TOKENS by using Replacement patterns for PDF file  path name


The code below should do the trick. If you have Devel installed, just open the devel/php page and execute this:

// Get all coupons on the site.
$coupons = db_select('commerce_coupon', 'c')
  ->fields('c', array('coupon_id'))
  ->execute();

// We will store here all coupon IDs, so we can delete them at once.
$coupon_ids = array();
foreach ($coupons as $coupon) {
  $coupon_ids[] = $coupon->coupon_id;
}

commerce_coupon_delete_multiple($coupon_ids);


How to make expandable text on clicking more button in views?

This will require some custom theming to accomplish:

In your view, don't trim the field, just show it all for now. This will mean if a user has JavaScript disabled they will still have access the all the content.
In order to enhance the interface as you've described for users with JavaScript enabled, you should take a look at this tutorial.
You will have to tweak things to get it working with your theme. If you're unsure about adding Javascript to a theme, check this out.


Install APC and Memcache and their extensions

If your stuck with shared hosting there are a couple of options to make Drupal faster.

Use some form of a file cache for the page cache. Boost & filecache's filecache_fast_pagecache option will serve cached pages a lot quicker than core does. For the other cache tables filecache or Drupal's core database cache might be quicker; you'll have to test to see what one works better on your shared hosting.
https://drupal.org/project/boost
https://drupal.org/project/filecache

Optimize your database. This is a post of things that can be done on the drupal side; there is a lot more that can be done if you can change the mysql side.
Drupal 7: Database select query FROM cache_bootstrap brings server down


Yes, what @remy said is true.
Inside /vendor/bin all "files" are actually symlinks. Real files are located elsewhere. However when copying those files (i.e. with Filezilla) instead of copying symlinks original files were copied.
I solved this by zipping whole bin dir, copying archive and unzipping in on remote server.
Zipping it with mac finder keeps sym links well. However, when zipping form command line most likely option --symlinks should be set:
zip --symlinks -r foo.zip foo/

https://serverfault.com/questions/265675/how-can-i-zip-compress-a-symlink


Auto-filling a form field with the sender page title

You could find the referring page by using $_SERVER['HTTP_REFERER'] in PHP and then lookup the node by using drupal_lookup_path and menu_get_object. At that point you then have the node object from the previous page and you can use "$node->title" to get the title you want.

$request_url =  $_SERVER['HTTP_REFERER'];
$host = $_SERVER['HTTP_HOST'] . "/";
$request_uri = explode($host,$request_url);
$path = drupal_lookup_path("source", $request_uri[1]);
$node = menu_get_object("node", 1, $path);

As far as how you put this into the webform, you could alter the submission using a hook or a specific component. I'm not aware of a module that lets you put PHP into a webform component. Potentially the Computed Field module (https://drupal.org/project/computed_field) could be of help.

Help from: How to get a node by its url alias?


I was experiencing this problem on two different test servers (different Debian and PHP versions) using data imported from our production server. All of the cache tables were emptied first, and I did try reinstalling Drupal using various methods. Couldn't find a solution anywhere.

What finally fixed it for me was emptying the registry and registry_file tables, then running update.php.  (Update didn't find any database changes, but it reset the registry - clearing the cache may have worked as well.)

Hope this helps someone - this problem was driving me crazy for two days.


Understanding database structure for auto-migration

You can skip migrating the following tables:

accesslog
cache_*
sessions
watchdog

All the above contains material that you generally don't want to migate across sites.

The contents of the tables for built-in search will be regeneated by cron if you don't migrate them, but it may take up a lot of resouces if you've a lot content. But if this is not a concern, you can also skip migrating:

search_*

As for table names, Drupal relies heavily on namespace dicipline to avoid collisions.  So a module named foobar should only create tables with a name that starts with foobar_ (or just foobar if it only creates a single table).  In other words, you can tell what tables in the database that "belongs" to what module by their name.  This goes for both core modules and for regular contributed modules.  As for custom modules (i.e. modules that is managed outside the Drupal.org framework, you may find exceptions to this naming convention - but only if they're written by bozos :-).

If you look at your database, you may discover a lot of tables with names starting with field_.  These are of course from the (core) Field module, but I mention these specifically because these are the tables used for custom content types that are created using "Fields in core" (a key Drupal feature).

As for interdependencies between tables, looking at the fields in the tables that belong to the same module is usually enough.  Getting familiar with the Schema API is also helpful.  But to be honest: Sometimes you need to sit down and read source code.

As for creating and dropping tables, well behaved modules create datebase tables using hook_schema (found inside the module's .install-file) upon installation, and automatically drop the same tables upon un-installation.

Note that just pushing a module with git doesn't install the module.  It just makes it available for installation.  To install it, you either do it manually (using the administrator's GUI), or script it using Drush.

It is also useful to know that there are clear rules in the Drupal community of practice that a module should only write to its own tables.  If a client module want to write to another module's table, it must do so through the module's API, not by interacting with the database.  Module interdependency is tracked in the module's .info-file.  This means, for instance, that you'll not be able to disable a service module a client module relies on (provided their interdependency has been correctly declared).


How do I pass multiple values to the command line?

$options = drush_get_option_list('options');

This will return something like array('apple') or array('apple','pear','orange').

Yeah, Drush does everything.


Delete/Edit selected record from rendered tabular form results

Not sure what your real question is (there is no "question" in your question ...), so consider editing your question to make that clear.

But I would give it a try to add a / in front of the 2 (similar) lines containing admin/mid-modules/component (so that they are changed to /admin/mid-modules/component). So both for the "delete" and the "edit".


hook_views_post_execute already has rendered fields


How to extend flood control in a custom module?

You need to do 3 things when you validate your password entry form:

Use flood_is_allowed() to check that the user hasn't already breached their flood limit and set a form error with form_set_error() if they have.
Use flood_register_event() to log failed attempts on incorrect password errors.
Use flood_clear_event() when the user enters the correct password.

You can also decide whether to do it based on uid, ipaddress, both of those, or something else entirely.

You can see the example of the user module in user_login_authenticate_validate() and user_login_final_validate(). That example may or may not be more complex than you need in your specific case.


JSON:API How to retrieve multiple values in a CONTAINS condition?

filter[profileStatusFilter][condition]
[path]=first_field&filter[profileStatusFilter2][condition]
[path]=second_field&filter[profileStatusFilter][condition]
[operator]=CONTAINS&filter[profileStatusFilter2][condition]
[operator]=CONTAINS&filter[profileStatusFilter][condition]
[value]=first_value&filter[profileStatusFilter2][condition]
[value]=second_value&filter[profileStatusFilter][condition][memberOf]=billing-
group&filter[profileStatusFilter2][condition][memberOf]=billing-group

Just change field name and values if you want change the custom name also here its profile status filter.


As a possible (but possibly not the best) solution it might be the 'account_switcher' service could help. It would elevate permissions for your cron job.

use Drupal\Core\Session\UserSession;

// call the account switcher service
$accountSwitcher = \Drupal::service('account_switcher');
// switch to the admin user
$accountSwitcher->switchTo(new UserSession(['uid' => 1]));

// run your code here

// switch back to old session
$accountSwitcher->switchBack();

zessx, please share your solution, if you've found one.

See original Q&A here.


If you are willing to have an extra field, consider using Corresponding Entity Reference.

  It syncs the entity reference between two entity types which have an entity reference to each other, so double editing entities is no longer needed. If one entity has a reference, the other entity also receives a reference to the saved entity if it is referenced in that entity.

So basically, if properly configured, it will give you "is referred by" field you mentioned in your last paragraph.

For Drupal 6, use Corresponding node references module.


How can I add a link on the "Structure" admin page?

You can go to /admin/structure/menu/manage/admin and add this link.


How to denote a user as a "system account"?

Have you had a look at using the API key authentication? This will enable you to login effectively without using a username + password combo.

See http://drupal.org/node/762092 for more information


Commerce: How to manage line item fields for custom product type?

There's an open feature request for precisely what you want in the queue for Commerce Customizable Products. In the meantime, you need to create a new product display node type for each product type and use the settings for the Add to Cart form display formatter to use the pertinent line item type in its forms.


How to change the look of second article at front page

One approach to do this is to use multiple views. One that displays only one node and a second one that displays the others, with an offset of one. Then it's easy to configure those views to use different view modes then. You can do that using Page Manager/Panels, Views attachments or possibly also core blocks.

One thing that can be a challenge to figure out is paging, depends on what you expect to see on the second page exactly. If you have paging, then a different approach might be necessary, for example by changing the view mode of the first view through code, through a preprocess hook or so.


Search Engine returning multiple 404s, Redirect 404 urls based on node id in the url

Try

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^articles/.*/.*/(.*)$ /node/$1 [R=301,L]

of not worked use your absolute URL

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^articles/.*/.*/(.*)$ http://www.yourdomin.com/node/$1 [R=301,L]


Add fields to image upload option in CKEditor

Caption and alt text are not a good example because they are stored where the image is used, not together with the file entity. What you are looking for is File Entity to store the source data in a field of the image file. For new projects you shouldn't use it anymore, because it is deprecated in favor of the Media entity. Media is now in core and when the module is enabled you can add fields directly to the media type Image (/admin/structure/media/manage/image/fields).

Out of the box CKeditor does only provide a button to add file images, which you want to replace with Media. To add media types you need the module Entity Embed until this feature is integrated into core.


How to get multifield(subfields value) in rules Drupal 7

First, you can try to "drill down" your entity and find the subfields. This is a great tutorial on how to drill down your data in rules. If it's not available, you can "Fetch an entity by id" into rules (under actions) and then it will be available.


Is it necessary to learn php in order to use drupal to manage my site?

No, it's not "necessary". Drupal core has a UI to perform its basic functions, as do most contributed modules.

Beyond that, it's totally up to you to say whether you need to learn PHP, based on the level of customisation you need in your site

If all the functionality you'll ever need can be provided through the UI of whatever modules you decide to use, then no, you won't need to learn PHP. If all of that functionality isn't provided "out-of-the-box", then yes, you'll need to learn PHP.

As with anything, your mileage will vary. The only possible way to answer this question properly is for you to get stuck in and try it out for yourself.


I haven't used this personally, but the Automatic Nodetitles module is designed to handle tasks like this.  If you have Token installed and enabled, you should be able to populate the autotitle using a field value.


Using drupal_add_feed() in template.php gives warning errors

You need instal Zen and STARTERKIT theme in (...sites\all\themes).Because STARTERKIT need Zen theme to work.


pass parameters drush_make or drush_make_process

The most stable way to call Drush from a php script is to use drush_invoke_process.

For example:

$values = drush_invoke_process('@none', 'make', array('someFile.make'), array('no-core' => TRUE, 'contrib-destination' => 'sites/all', 'yes' => TRUE));


How can I add markup to a link in node links?

Unfortunately the object PluralTranslatableMarkup has no method to get the protected value count. The serialization was fixed to provide the count value, see issue https://www.drupal.org/node/2844181, but the class is still missing it's own getArguments() to extend it with the count value. You could file an issue and wait for a fix or use this work around with reflection:

  if ($title instanceof \Drupal\Core\StringTranslation\PluralTranslatableMarkup) {
    $reflection = new ReflectionClass($title);
    $property = $reflection->getProperty('count');
    $property->setAccessible(TRUE);
    $count = $property->getValue($title);
  }


How to add a single taxonomy term as a body class in Drupal 8

i found a solution which worked perfectly for me. Add this in your .theme file and replace mytheme_preprocess_html by your theme name and field_section by name of your taxonomy field.

[https://gist.github.com/awasson/d8ef8d7c1b64b2ccb8a0][1]

<?php

    /**
     * Prepares variables for the html.html.twig template.
     */

    use Drupal\taxonomy\Entity\Term;
    use Drupal\Component\Utility\Html;

    function mytheme_preprocess_html(&$variables) {

      if ($node = \Drupal::routeMatch()->getParameter('node')) {

        /**
         * Get the term id from the 'field_section' taxonomy field.
         * If greater than zero, load the term and acquire the name value
         * as a css safe value.
        */
        if($node->hasField('field_section')) {
          $tid = $node->get('field_section')->target_id;
          if($tid > 0) {
            $term_object = Term::load($tid);
            $variables['attributes']['class'][] = 'terms--' . Html::getClass($term_object->get('name')->value);
          }
        }

        /**
         * Get the node id from the node object.
         * If greater than zero, add the node id to body classes
        */
        $nid = $node->get('nid')->value;
        if($nid > 0) {
          $variables['attributes']['class'][] = 'page--node-' . $nid;
        }
      }

    }


how to get the values of entity reference fields of a content type in a node page?

You can try this thing

// $node represents the node object
// field_songs is the field used in content type to reference field.
$wrapper = entity_metadata_wrapper('node', $node);
$songs = $wrapper->field_songs->value();

Now in $songs you will have each songs object and you can print what ever information you want to print from it.


this link "ask for more info" needs the nid appended as query string. and then in the form this can be used.


Why is smtp not sending emails via SendGrid?

We use SendGrid with SMTP Authentication Support and have not encountered any problems.

SendGrid may not allow unencrypted connections on port 587, depending on your package. That is the port for TLS/STARTTLS, so if you want to use port 587, you should select use TLS under Use encrypted protocol. This is how all of our sites that use SendGrid are set up.

One trick that can trip you up is the configuration of Mail System. If you use Mime Mail or another system that requires Mail System to be installed, you must configure Mail System to use SMTP explicitly, or it will fall back to Drupal's default mailer (PHP mail())

For a quick out of the box, you need to configure Mail System  (/admin/config/system/mailsystem on Drupal 7) to use SmtpMailSystem for your module class (for example as the Mime Mail module class, or as the Site-wide default MailSystemInterface class).

For an alternative integration option, there is a SendGrid Integration module which uses the API rather than plain SMTP.


Update pagination after hook_apachesolr_process_results()

Instead of using hook_apachesolr_process_results() I figured it was better to use hook_apachesolr_update_index instead.

Following the guidance here: http://www.phase2technology.com/blog/filtering-apache-solr-search-results-based-on-dynamic-fields/

I am now able to create a filter using hook_apachesolr_modify_query that will return the correct results and pagination.


The view mode is in the vars:

function MYMODULE_preprocess_node(&$vars) {
    $view_mode = $vars['view_mode'];
}

See template_preprocess_node() or node.html.twig for more info.


Creating content types with fields that are other content types?

In future it would help to know what version of Drupal you are using.

In D6 you can use Node Reference CCK field, which creates a cck select list, auto complete, radio buttons or checkboxes listing the node types you have selected to be referenced.

There you could use your autocomplete form, type the users name and add them to the project.

This module however no longer exists in D7, instead have a look at these modules which could do the same or similar:

http://drupal.org/project/references

http://drupal.org/project/Relation

http://drupal.org/project/entityreference


How to force a field to allow unlimited number of values using Field API?

You mean for a field type that you created yourself?

There is no real API to declare that, the only thing you can do is alter the add/edit field form.

I've already done this myself for the Properties module; here is the code (source):

function properties_form_field_ui_field_edit_form_alter(&$form, &$form_state) {
  if ($form['#field']['type'] == 'properties') {
    // Hide the cardinality setting on the field settings for properties fields.
    $form['field']['cardinality']['#default_value'] = FIELD_CARDINALITY_UNLIMITED;
    $form['field']['#access'] = FALSE;
  }
}

(Don't forget to flush the cache after changing form_alter hooks and, if it's an instance setting, delete and recreate the instance to remove the previous default)


Add class-element to a link though a module (or can I implement theme_link in a module instead of in a theme)?

What I understand is that you want to have a class in every link that comes on the site.
I believe, you can achieve this by skinr module - https://drupal.org/project/skinr, which not only adds up classes but also provides you UI to achieve the same.

Also, in module, you can try this.

/**
 * Implements hook_preprocess_HOOK
 */
function MODULENAME_preprocess_menu_link (&$variables) {
  if ($variables['element']['#original_link']['menu_name'] == 'main-menu') {
    $variables['element']['#title'] = '<i class="icon-' . _sanitize_words($variables['element']['#title']) . '"></i>' . $variables['element']['#title'];
  }
}

The above could should work, Worked for me atleast :)


Glossary view: Show all results separated by letter

Check out the Glossary module.

  The glossary module scans posts for glossary terms (including
  synonyms). The glossary indicator is inserted after every found term,
  or the term itself is turned into an indicator depending on the site
  settings. By hovering over the indicator, users may learn the
  definition of that term. Clicking the indicator leads the user to that
  term presented within the whole glossary or directly to the detailed
  description of the term, if available.

or

Lexicon

  A lexicon is a stock of terms used in a particular profession, subject
  or style; a vocabulary. The Lexicon module generates one or more
  Lexicon pages based on terms in taxonomies and optionally marks terms
  in the content and links them to the appropriate Lexicon page.

or

take a look at G2 Glossary module.


Change print icon programmically through template.php

blog.kalamuna.com helped me a lot. I just changed the $icon value.

Here is the code that I put in the PHP tags in my template file

//Change print icon in print icon
/**
 * Format the Printer-friendly link
 *
 * @return array
 *   An associative array containing:
 *   - text: The content of the link
 *   - html: TRUE if the text contains HTML tags, FALSE if it's plain text
 *   - attributes: several attributes of the link tag (title, class, target,
 *     onclick, rel)
 *
 * @see _print_ui_fill_attributes()
 * @ingroup themeable
 * @ingroup print_themeable
 */
function subtheme_print_ui_format_link($vars) {
  $format = $vars['format'];
  $path = '/images/print_icon.png'; //path to file, relative to theme YOUR_THEME

  foreach (module_implements('print_link') as $module) {
    $function = $module . '_print_link';
    if (function_exists($function)) {
      $link = call_user_func_array($function, array());

      if ($link['format'] == $format) {
        $link_class = variable_get('print_' . $link['format'] . '_link_class', $link['class']);

        $new_window = FALSE;
        $func = $module . '_print_new_window_alter';
        if (function_exists($func)) {
          $func($new_window, $link['format']);
        }

        $show_link = variable_get('print_' . $link['format'] . '_show_link', PRINT_UI_SHOW_LINK_DEFAULT);
        $link_text = filter_xss(variable_get('print_' . $link['format'] . '_link_text', $link['text']));

        if ($show_link >= 2) {
          // Work out which icon we want to show based on the link's format.
          switch ($link['format']){
            case 'html':
              $icon_name = 'print';
              break;

            case 'mail':
              $icon_name = 'envelope-o';
              break;

            case 'pdf':
              $icon_name = 'file-pdf-o';
              break;
          }

          // Build the icon.
          $path = '/' . drupal_get_path('theme', 'YOUR_THEME') . $path; //the path is relative to the theme 'YOUR_THEME'
          $icon = "<img src='" . $path . "' class='print-icon " . $link_class . "' alt='Print this page' />";

          // Show the icon with or without text, depending on config settings.
          switch ($show_link) {
            case 2:
              $text = $icon;
              break;
            case 3:
              $text = $icon . ' ' . $link_text;
              break;
          }
          $html = TRUE;
        }
        else {
          $text = $link_text;
          $html = FALSE;
        }

        return array(
          'text' => $text,
          'html' => $html,
          'attributes' => _print_ui_fill_attributes($link['description'], strip_tags($link_class), $new_window),
        );
      }
    }
  }
}


Rules send email containing tokens from submitted node displays token for empty field

you may use PhP in your send mail rule action to check if your field is empty.

Be careful it's a bit tricky because token is not actually empty when the field is empty, it's just not computed, as you saw when you tested.

Unfortunately, the token will be rendered, if field not empty, whatever you put around it in PhP, even ' or ".

So, it's not really clean, but the way I see it is explode and then check whatever you want (for my part I use here only the first part, "[node") :

<?php
// Explode your token (or your value, you don't know yet)
$a = explode(':',"[node:body]");

// Check if first part is [node
if($a[0] != '[node') { ?>

[node:body]

//Don't forget to close the if() statement
<? } ?>

Not very good if you have to check this on many fields, NOT CLEAN at all in fact, but working :D


How to add e-mails in 2 different databases in drupal 7

You have an option in Simplenews to subscribe the user on registration since 6-x.2.x : http://drupal.org/node/658242.


Display file description in view using Download Count

I have figured it out, I had to add another relationship for the fields file id "field_attachments:fid" and then applied that relationship to all of the other fields.

Then I changed the aggregation settings for the attachment description field to group by 'fid' with 'display' and 'description' as additional grouping columns.

Now my view output only displays the matching description of the file in that row.


How can a description be added to the body field summary widget in node edit form?

I assume you're using Drupal 8.
Try the below in your hook alter. This also assumes the usage of the default body field in use:
use Drupal\Core\StringTranslation\TranslatableMarkup;

// Ensure summary field existence.
if (isset($form['body']['widget'][0]['summary'])) {
  $form['body']['widget'][0]['summary']['#description'] = new TranslatableMarkup('Your summary description goes here.');
}


Have a profile field item from user registration show on a users page

One way you can do this is if you have a custom template in your theme for user profiles. Creating a custom user profile template

Basically, you can overwrite the entire layout of the user profile this way. And then, you can output profile fields however you like by simply printing them. For instance:

<?php print $account->CHECKBOX_FIELD_NAME; ?>

This will allow anyone visiting the profile to view the results.

If you wish to display this to only users of a specific role, you would want to wrap the above code in an if and check what the viewing users role it.  For example, something like this

// Check to see if $user has the administrator role.
   if (in_array('administrator', array_values($user->roles))) {
    CHECKBOX_FIELD_NAME; ?>
   }
  ?>


Cron job run, but module updates not checked - how to automate?

Looking at the code of update_cron(), I notice that the function checks for updates if there aren't cached data or if the update interval is past.

function update_cron() {
  $frequency = variable_get('update_check_frequency', 1);
  $interval = 60 * 60 * 24 * $frequency;
  // Cron should check for updates if there is no update data cached or if the
  // configured update interval has elapsed.
  if (!_update_cache_get('update_available_releases') || ((time() - variable_get('update_last_check', 0)) > $interval)) {
    update_refresh();
    _update_cron_notify();
  }
}

By default, updates are checked once per day; if you want Drupal checks for updates twice per day, you can change the value of the "update_check_frequency" variable to 0.5.
As the setting page doesn't allow you to set a value that is lower than 1, you can change the value of that variable with variable_get('update_check_frequency', 0.5). Cron tasks needs to be executed at least twice per day, or the trick doesn't work.
You can also invalidate the cache, and force update.module to check for updates the next time the cron tasks run, by visiting the page that lists all the modules and clicking on the "Save" button; alternatively, you can call update_invalidate_cache().


Updating it from the admin/content page works as normal. I select what needs to be updated and scroll to the bottom to "Bulk operations -> Update URL alias".

I don't need to delete any URL aliases manually


How can I make views page with unique dates?

Im not sure i fully understand your question. However, assuming you want to simply have a list of dates.

Edit the view
Make sure the format uses fields
In the field section add or remove field as required (fields can be removed using the rearrange menu item , under the arrow next to add)


drush has no option to clear queues, there is just drush queue-list and drush queue-run. However, you can use it to delete the corresponding queue records from the database:

Use drush queue-list to find out the name of the queue you want to clear. In my case, it is message_subscribe.
Use a command like this, replacing with your queue's name accordingly:

drush sqlq "DELETE FROM queue WHERE name='message_subscribe'"

Confirm with drush queue-list that the queue in question now has zero items in it.

This solution is quite similar to @batigolix's, just that it clears a specific queue instead of all queues.

Careful. Like @batigolix said, take care not to lose data! This solution might not be for a production environment …


Attach a form input to a node that will be submitted by multiple users

You can achieve that by the Webform module. or
Try the Simple Contest module

Simple Contest module provides contest system for Drupal websites.
Features:

contests are nodes. multiple contests of multiple contest type can be    run same time
Two winner types : Users & Node, that means winners can be "user" or    node"
multiple winners can be chosen by ranking/weight
Supports both automatic and manual winners selection
Winner chosen rule will be based on View. so it is up to you to    decide how the winner will be selected
Modules integration with Views, Token, Rules, Userpoints, Date    Repeat, Commerce Coupon, UC Gift Certificate & UC Coupon
Token integration and customized E-mail notifications

Please note the this module is in dev version. So try that in local (test) environment.


Where can I find the code for the user menu block?

In user.module, all functions with prefix user_block_ in name.


Coloring rows in returned drupal search results

I would create your search results page using views, this has the odd/even class functionality built-in. The current code you provided won't work since the $inc value starts as 0 and there is no loop where $inc++ occurs so everytime this template is loaded $inc will start as 0 and end as 1.


How do I make the page created from my module visible only to anonymous users?

'access arguments' => array('access page_prog content'),


Remove "read more" when there is no more text to read

Neither of the other answers actually addresses the question, which is how to turn off "read more" selectively depending on whether there is more to read or not.

The standard read more link, as the comments in NodeViewBuilder say, is always displayed on a teaser by default because there is no (easy) way to know how the teaser content differs from the full view. Your content type might have several other text fields apart from the body which are only shown on the full page view.

However, it should be possible to implement a custom "read more" link that has the behaviour you seem to be asking for. I don't think anyone has implemented one yet, but the most fruitful approach would be a modest extension of the "summary or trimmed" field formatter, although you could probably also do something in a preprocess hook in your theme.

Edit: A demonstration module is up on github now. It's not perfect and I would like to refactor it and possibly make it more general-purpose but it works for the simplest case.


One way to accomplish this would be to change the view from showing content to showing fields. You can then add the fields that you want to show, title and image.

To change the link of the title, you can add the nid as a field, hide it, and then rewrite the output of the title field to include the custom path and nid in the link.

To find the template files of the view, you need to click on the "Advanced" tab and look for "Theme: Information". You'd need a sub-theme to register the template file being overwritten. Drupal Sub-theming

To overwrite it in a module, you could use a pre render hook and modify the rows on the result fields.


I have never really used multi site much, but I have read the documentation multiple times nevertheless.

It always was my understanding that the default folder was reserved for the default site, and that all other folders should be placed next to it, not inside of it.

Next to that, the documentation implies that your folder name should match a certain pattern, based on the site url.

Instead of using www_d8multisite_com/sites/default/ms1 I'd try using www_d8multisite_com/sites/d8ms1.com instead.


How to do path aliases for views like news/%?

That is quite a tricky one.

Two possible solutions:

1)
Use page manager, create a context for each content type, and then use this module to generate the aliases): https://www.drupal.org/project/page_manager_pathauto (note: no Drupal 8 version)

2) Add/remove/modify the aliases yourself with an update hook.  So when a node is updated, you create/update/delete the corresponding path aliases.


You're looking for the Head Module:

  This module provides a range of metatags that can be added to the
  document head of each available theme.

  In an attempt to keep themes clear of anything that could be
  considered optional, i have aggregated all the frontend related
  metatags you could ever need into one advanced theme settings page
  which can be found at admin/appearance/advanced


Organic Groups (7.23) and D7 | drush or cmdline integration?

I started, but never had time to finish Drush commands for og-6.x-1.x.  Please see https://drupal.org/node/1090438 for the preliminary implementation.  I don't know why no one else has picked this up; I agree it would be useful.

For og-7.x-2.x, I do some programmatic operations in my sandbox project https://drupal.org/sandbox/greg1anderson/2049677.  These are not broken out into direct og operations, but it might serve as a starting point for someone who wanted to pick up the task of adding Drush commands to organic groups.

Finally, for anyone who wants to quickly make a Drush command from a template, see https://drupal.org/project/drushify.


Struggling with Feeds Importer to custom content type

So I gave up with Feeds Importer.
Despite a clean install, I could not get the feed description to go into any other target field other than description.

Despite setting the text format as Full HTML, it defaulted back to Filtered HTML and would not show the image in the feed. I had to edit each node, change the text format and then it would display.

So, I reverted back to the core aggregator and after some head scratching with CSS, got it to do what I wanted..

You can see the initial result at http://bedsastro.org.uk - this will be revised and updated shortly, but at least I got it working!


Programatically insert field value of for a taxonomy term

Should just need to do:

$new_term = \Drupal\taxonomy\Entity\Term::create([
 'vid' => 'field_school_name',
 'name' => 'ABCD',
 'field_school_id' => '1234'
]);


Is there a way to limit where a block displays based on a query in the URL?

You can implement a condition plugin that does just that and then configure your block to use that condition, we did something similar once:

/**
 * Condition on the page query param.
 *
 * @Condition(
 *   id = "yourproject__first_page",
 *   label = @Translation("First page (by url query param)")
 * )
 */
class FirstPage extends ConditionPluginBase {

  /**
   * {@inheritdoc}
   */
  public function evaluate() {
    $match = !\Drupal::request()->query->get('page');
    return $this->configuration['negate'] ? !$match : $match;
  }

  /**
   * {@inheritdoc}
   */
  public function summary() {
    return $this->t($this->configuration['negate'] ? 'The %param parameter is not %value' : 'The %param parameter is %value or empty', ['%param' => 'page', '%value' => 0]);
  }

}


How would I clear values in ajax loaded select options?

SOLVED

/**
 * The ajax call to return data for the printer model select.
 * @return array             An array of settings.
 */
function first_ajax_callback(&$form, &$form_state) {
  // Reset conditional select values.
  $form['field_printer_model_value']['#value'] = array('All' => 'Select Printer Model');
  $form['field_printer_type_tid']['#value'] = array('All' => 'Select Device Type');

  // $commands = array();
  $commands[] = ajax_command_replace("#second_dropdown", drupal_render($form['field_printer_type_tid']));
  $commands[] = ajax_command_replace("#third_dropdown", drupal_render($form['field_printer_model_value']));

  return array('#type' => 'ajax', '#commands' => $commands);
}

In the above call I set the #value of the selects I want to reset. These lines properly reset two later dependent selects:

$form['field_printer_model_value']['#value'] = array('All' => 'Select Printer Model');
$form['field_printer_type_tid']['#value'] = array('All' => 'Select Device Type');


Autocomplete not working for Search API with Solr - Drupal 7

The README.txt file in the search_api_autocomplete module provides the following information:

Necessary setup

After having installed and enabled the module, you have to do some
administrative steps to activate the autocomplete functionality. Autocompletion
can be enabled and configured for each search separately.

To activate autocompletion for an index's searches, go to the index's
„Autocomplete“ tab. There, you see all available searches for the index and can
enable (and afterwards configure) autocompletion for each of them. All fulltext
key fields on the searches should then become autocompletion fields.


What can cause an incorrect base_url to intermittently appear for images?

I have had a very similar issue before.

Basically, the problem I had was that the image path was saved as  url, instead of being a relative path. If this is the case, the fix is fairly simple, simply go look at that node's attributes in the database, and change the url path to a relative paths.

If you are in doubt, a quick and dirty way to see if this is really the problem:

Do a DB dump, with mysqldump or whatever you use,
grep in that file for "http://localhost"

grep -b3 -a3 "http://localhost" yoursqlfile.sql

The b and a flag are for the number of lines returned upon a text match before and after the match it is optional and can be tweaked to higher values if wanted/needed.

Now, if there is any reference in the sql data pointing to  your http://localhost, in your node meta-data these 2 simple steps will quickly help identify where the offending nodes are.  Just note the table and field names that grep found & the nid's and go change the values to relative paths using either the commandline, a script or php-myadmin!

Of course, there are many ways to do this I just pointed out a very general way of fixing your data so it is portable.

Good-luck, happy coding.


Find out module versions through database dump

Import the dump file into mysql database. Create a new database in your localhost and import the db using your backup file
Browse System table.
Run below query

SELECT info
FROM  system
WHERE  filename LIKE  '%ctools.module%'
ORDER BY  system.name ASC
LIMIT 0 , 30
You will see version information in info column. Search for "Version". Above information is serialized.
For Example, As you see below "Ctools" module is 6.x-1.11 version. You can do same for panels module by changing query.


When you're configuring the filter, at the top, select For This block (override) or This Page (override)

Example:


I hope i understand the question correctly:

In views you can check the option "Strip html tags" in options.


In theming the use of render() is correct, you can't use a different render method. The problem is that many blocks are placeholdered and you can't determine at the point the page template is rendered in which context the placeholdered block might be rendered in future. Probably then with a different user logged in because blocks cached per user are placeholdered by default.
The code in your question thinks the region is empty because striptags removes placeholders which usually are formatted as HTML tag.
You can change this at the expense of cache performance by adjusting the cacheablity of the blocks involved or customizing the auto-placerholder condition site-wide.
See https://www.drupal.org/docs/8/api/render-api/auto-placeholdering


form or content type creation interface?

You don't usually create a custom module just to have fancy fields in a form. If it can be done with fields, you do it with fields (i.e. you use the content type creation UI). For data types that doesn't exist in the core (e.g. links and entity references) there is almost always a module that let you add fields of those types to a standard Drupal entity.

You only create a custom content type if you want to do a lot more than just capturing the data. With "more", I means such things as computing aggregates, transforming it, combining it with other data, visualizing it, etc.

My rule of thumb is: If it can be done with fields and contributed modules - do it with fields.  If it can't be done with fields, create a custom module.  And in that case, I let the custom module also manage the form and data validation (but built-in top of the Form API).

If you want do just want to interact with the creating, validation or deletion of an entity, there is a lot of good examples of what you can do in the entity_example.module.

For instance, to have a submit handler that does extra validation before saving, look at function entity_example_basic_form_validate.


You also put another condition in your query

"$rl_query->condition('fci.field_story_target_id', $node->nid);"

You can check by commenting this line.


How to add a button or link to perform an action on a node with node_view?

You can implement the hook_node_view() like the following code:

function YOUR_MODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'CONTENT_TYPE_NAME') {
    $form = drupal_get_form('redirect_button_form');
    $node->content['redirect_button'] = $form;
 }
}

function redirect_button_form($form, &$form_submit) {
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('New Item'),
    );
    return $form;
}

function redirect_button_form_submit($form, &$form_state) {
    //here the path where you need to go
    $path = 'node/add/CONTENT_TYPE_NAME';
    drupal_goto($path);
}


How do I limit the node count of a content type to one per user?

You can use the Node Limit module for that:

  The Node Limit module allows administrators to restrict the number of nodes of a specific type that roles or users may create. For example, if a site has an "Advertiser" role that can create "advertisement" nodes, then the node limit administrator can restrict all users in that role to a specific number of nodes. He may also restrict users on a per-user basis.


Try changing your code to use hook_entity_insert which is run after the saving to the database:
 https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_insert/8.2.x

As the reason you can't get the entity ID in presave is because if its a new entity then the ID hasn't been generated by the autoincrement ID field in the database yet so an ID doesn't exist for it until it's saved for the first time


Behaviors/JQuery: What's the standard/convention in Drupal 7 for running Jquery code on event *OTHER* than DOM ready?

Using .load() on element to attach event handler in your behaviors should not be a problem. Using it directly to window outside a behavior, for instance to wait for all images to be loaded, should be okay too.

As pointed by Clive in the comment, Drupal behaviors are to be used in replacement of $.ready(), not $(window).load(). However, if content (ie. new DOM elements) is added to the page after page load (AJAX calls, content generated from JavaScript, etc.), handlers for $.ready() will not be called and will not have a chance to process the added DOM elements. While the attach() method of all behaviors is also called when this happen. With a parent of the added DOM elements as context.

Behaviors can also have a detach() method which is called when DOM element are removed or before form serialization. This us, for instance, used to properly destroy WYSIWYG editors when their textarea are removed from the DOM and to prepare the POSTed data hen their form are submitted.

Off course, this rely on the JavaScript doing the addition/removal/serialization to properly call Drupal.attachBehaviors() and Drupal.detachBehabiors(). Something that is done by Drupal core (including form handling and the Drupal AJAX Framework) and properly written contrib modules.

I'm not familiar with the load event and its behavior with content added after the first time it is triggered. If it does not fire multiple times, re-registering the handler in a behavior attach() method may be required to ensure newly added image are also processed.


xml feed parser from multiple sources, multiple url-source xml importers

To me this seems like an exact use case for Feeds plus Feeds XPath Parser.  It will be possible to map your custom XML spec to various fields and import content from as many sources as you want into nodes of the same content type.  I posted an answer to another question which may give guidance on how to use it.
Feeds:

Import or aggregate data as nodes, users, taxonomy terms or simple database records.

One-off imports and periodic aggregation of content

Import or aggregate RSS/Atom feeds

Import or aggregate CSV files

Import or aggregate OPML files

PubSubHubbub support

Create nodes, users, taxonomy terms or simple database records from import

Extensible to import any other kind of content

Granular mapping of input elements to Drupal content elements

Exportable configurations

Batched import for large files

Feeds XPath Parser:

Feeds XPath Parser is a Feeds plugin for parsing XML and HTML documents. It enables site builders to leverage the power of Feeds to easily import data from complex, external data sources. Each element you wish to extract is setup using configurable mapping queries, saving time for developers who would otherwise have to code complex, specific-use modules. It also enables end-users to build web scrapers and other useful tools within Drupal.


how to fetch user related tables from live sever with drush sql-sync

It is not recommended to push your database from dev to live.  Instead, push just the code from dev -> stage -> live, and pull the database in the other direction.

There are a number of solutions for moving content from dev or staging to live.  One option is the content staging module; other people use feeds to import new data.


Customized as it may be, it worked:

Using VBO and performing a hook_form_alter onto the exposed filter form I was able to add a hidden field.

Using javascript, I store the values of the selected entities (derived from the checkboxes attributes) into the hidden field. If the user triggers the exposed form submission, the values remain and on the new page load I use the same values to recheck the checkboxes thus providing the illusion that the values got preserved.

Downside is the unavoidable use of javascript and the possible huge URL.

If anyone has anything better to propose or make the exposed form NOT place it's parameters as $_GET parameters in the url I'd be glad :)


How can I add or remove links to nodes in a list depending on the values of some of the fields

This is probably one of those questions that might fall under opinion-based, but I'll give my answer.

The answer really depends on your needs. It comes down to the question, does stub content impact display or workflow (editing, moderating, viewing, etc.) around the content? In either case, you'll want a centralized piece of logic (e.g. mytheme_is_stub() or mymodule_is_stub() function) that determines if the content meet your stub criteria.

If it impacts just the display then you want a theme; you can use your centralized logic to determine when/where to alter rendering of content.

If it impacts the workflow (e.g. you want to prevent an author from creating stub content or alert them about stub content) then you want a module; you can use your centralized logic to determine when/where to alter workflow around the content.

From your description (altering links, search display, etc.), it sounds like your only concern is display, if that's the case then you want a theme.


Every link except home directes to 'Not found' page?

You are missing (or having a malformed) htaccess file.

You can download a .htaccess file directly from drupal.org with the following link: https://raw.githubusercontent.com/drupal/drupal/8.2.x/.htaccess

If you want an htaccess file for a different disk version then you can change the version number in the above link.


Permissions to Upload images in text field

You need to use Full HTML in order to accept upload images in a text box.
Basic HTML doesn't allow img tag.

The other option is to add img tag in basic Html format, check:

  admin/config/content/formats/manage/basic_html

or create a new text format which will be available to other roles and will allow img tag.


Page title block hidden on custom route, panel or view pages when content type is chosen in block visibility settings

Because they are not a page of that node type. This filter doesn't just apply to node/*, it applies to all pages. And if there is no node object, the condition will always be false.

If you need something that is true on all non-node pages but for node pages only for a specific ype, you need to define your own condition plugin or use hook_block_access().


The following should suffice:

$query = \Drupal::entityQuery('node')
  ->condition('type', 'beacons');
$entity_ids = $query->execute();

Here is a drush one-liner to test this on my D8 instance, where I have one article node:

 drush ev "var_dump(\\Drupal::entityQuery('node')->condition('type','article')->execute());"

Gives me:

array(1) {
  [101]=>
  string(3) "101"
}

where 101 is the nid of the article node.

Good luck!


If you enable the Display Suite extras module you can create a display suite field that contains a block. It's included in the DS module you just have to enable it.


I want to display one content type inside of another

What I would do is the combination of the comments above.

To your team 'Team member' content type add entity reference field with reference to 'Our Team' content type
Create a view that lists all of your team members (regardless the team for now).
In 'Contextual filters' under 'Advanced' settings of your view that you created in 2. add the field the you created in 1.
In the settings of that filter select 'Provide default value' and choose 'Content ID from URL'
Save your view.
Add view field to your 'Our Team' content type, in the settings of that field select 'Always display default value' and below select the view that you created in 2.

As long as I understood you correctly this should do the trick.


How do I say to Twig where to look for the template files?

What you found is the class used from Twig to load the template files from the file system, but what Drupal uses is its own class derived from that,  Drupal\Core\Template\Loader\FileSystemLoader, which is the default class implementing the twig.loader.filesystem service. Its only purpose is adding a namespace for each theme and module enabled from a Drupal site, so that is possible to reference a template file as @block/block.html.twig.

For how I understand it, replacing the class implementing that service with a class derived from the default implementation, you could be able to reference
a template in a different directory with, for example, @external_directory/template.html.twig.

See  FilesystemLoader::__construct() for how Drupal adds new namespaces, and Altering existing services, providing dynamic services for how to alter that service to use a different class.


Add meta tag description, page title and abstract programatically

In your theme's template.php file, you could add something like

/**
 * Implements hook_preprocess_html
 */
function THEME_NAME_preprocess_html(&$vars) {

  if (current_path() == 'my/custom/path') {
    $description = array(
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'description',
        'content' => 'here all description goes',
      )
    );
    drupal_add_html_head($description, 'description');
  }

}

Clear cache to register new preprocess function.


Hiding an image field based on theme in Drupal 7

It can be done in node.tpl.php

hide($content['field_image']);

or in hook_preprocess_node

hide($variables['content']['field_image']);

It works with views as well if you are using content row plugin.
For fields you have to override views-view-fields.tpl.php and remove image field from $fields variable.

unset($fields['field_image']);

Also take look at this modules:

https://drupal.org/project/cs_adaptive_image

https://drupal.org/project/adaptive_image


Have you considered helping yourself with this similar question?

showing an image field from solr index on custom solr search page

To display image in your search-result.tpl.php you can follow below link also.

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


How to group and merge results together in Views?

You can achieve this in following ways,

1) Choose your views format as table under Format 'Format: Table', Then click settings. You can find a table listing your selected fields. near to each field there is an option to choose column. There choose your  Title B s column to Title A and in the separator provide '&' . Ensure Grouping field has chose. Now you will get a display in following format
Group 1:
Title A & Title B

OR

2) After grouping, Choose Exclude from display option for your Title A  field. Then for second field choose Rewrite results. There you can find Replacement patterns. Use your token in appropriate format. eg. [title] & [nid]

Hope this may helps you


Theme specific form field for custom content type

If you want to do it in template.php, you would use THEMENAME_field__fieldname__contenttypename() as theme function. If you like to use a special template file, you would name it field--fieldname--contenttypename.tpl.php and put it into yours themes template folder.

All needed information can be found in Drupal API documentation.


Is $page only an array important for theming purposes?

There is just a type of render array, and it is the one described in drupal_render(); the form API extends the render array with properties necessary to validate/submit a form element. The purpose of a render array is just to theme elements present in a page; it is not used for other purposes, if not rendering/theming.

The output of a module is always part of a render array, except when a module implements code similar to the following one.

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

  function mymodule_abc_view() {
    echo "<title>Error</title>Error page";
    drupal_exit();
  }

If you visit http://example.com/abc/def, there isn't any render array involved in rendering the page.


How can I expose Drupal data to external applications?

One of the most popular solutions is the Services module. It takes a little bit of set-up and know-how but it's very flexible in what it can output and what formats you need it. It's the solution we used at Palantir.net to provide data to our DrupalCon Chicago Android and iOS apps.


Rules: Load List of Entities by Object or Entity ID (Performance)

Using Solution A will pretty sure have performance implications, so I wouldn't recommend that approach "to load hundreds or thousands of Users". Below is a blueprint of yet another approach (another option that you could considered, up to you to decide if it is "better"), which will allow you to reduce the performance risk significantly ...

Step 1 - Refine your view

Adapt the VBO view you already have, by limiting the results of that view to the first X users only. Pick a value for X that fits your needs, to start make it small enough and increase later on as much as you feel comfortable with.

Also adapt the views filter, to no longer include the users that have been processed already (by the Rules Component described in the next steps).

Step 2 - Create a Rules Component

Create a custom Rules Component which performs the Rules Actions as in your Solution "B" or "C". If the value of X is small enough, you can do some experiments with either of these solutions (B or C), i.e. to find out what happens if you increase the value of X (and based on that decide for yourself which one works best). Note that the list to be processed is limited to "X users" only (i.e. those that are contained in your views results from the previous step).

Add an additional Rules Action in your Rules Component, to actually reschedule the execution of this Rules Component itself after a few seconds or minutes (whatever fits). And trigger the very first execution of this Rules Component via a custom rule that is triggered "When any user of a Company purchases membership" (as in your question, I bet you have some appropriate Rules Event for that).

Step 3 - Stop rescheduling the Rules Component when the time is right

Also add a Rules Condition in the Rules Component of the previous step, to "Check the number of results returned by a VBO view" (using the same VBO view). The actual number of results should be at least 1. If there are zero results, then the Rules Actions of this Rules Component will not be performed, which is what we want. Since it will also prevent the the rules component reschedules itself when all users have been processed.

Step 4 - Review the frequency of your cron jobs

Make sure your cron job runs frequent enough, because each execution of your scheduled Rules Component will actually only happen when cron runs.

Conclusion: because this approach is based on the Rules Scheduler, the elapsed time will be longer, for sure. But the advantage of it is that, as compared to any of your 3 solutions as in your question, the poor user "of the Company who purchased the membership", will not have to wait for the rule to complete execution, before being able to do anything else on the site.

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


Display different content on node pages depending on user role

Showing different content on the same page to user depending on role could be accomplished with the Panels module like so:

Install the Panels module and its dependencies.
Go to admin » structure » panels.
Enable and edit the page "node_view" template.
Click "add new variant".
Click "continue" on each screen until there is a button with "Add variant." Click "Add variant".
Under panel » content, click the gear in the upper left to add a panel of content for the logged in user to see. Save.
Click the gear in the upper right of the new content to get a menu. Select visibility rules » add new rule. Select role and set it how you want. Save.
If you want to show something different to anonymous users, repeat step 6 and 7 to add content and make it visible only to anonymous users.
Don't forget to save.


How do I access URL parameters from my custom module?

The function arg() will do that for you. For example, in path http://siteurl/products/%items,

arg(0) will have the value products (first value after your $base_url)
arg(1) will have the value of %items (second value).

You might then just apply your logic, in this this case you could do the check arg(1).


Twig/Drupal caching and dynamic variables

My understanding is that this doesn't vary on the same URL, so both page_cache and dynamic_page_cache should be fine. However, each node is also cached on its own, a and that's your problem here.

As 4k4 said in the comment, you should be able to vary the cache with this: $variables['#cache']['contexts'][] = 'url'.

That's rather problematic however, because it means that every node needs to be cached differently on every page, which results in a huge amount of variations that fill up your cache tables.

You could define your own cache context for whether you are on the node page of a given node. Core actually should provide a cache context for that, since it has a similar problem when you'd e.g. use the default view mode somewhere else than on the node/N page. But it doesn't, there's an open issue for that.

As mentioned, the easiest fix is probably to use JS for this.


Change Input Field Value using Hook Form Alter (User Login Block)

Put this in your module:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login_block') {
    $form['name']['#size'] = 10;
    $form['pass']['#size'] = 10;
  }
}

Also hook_form_user_login_block_alter can be used, then you don't need to check the form_id.

Remember to clear the cache, if you are not already using hook_form_alter.


Running two Drupal sites off the same database: Is it possible?

Is it possible? Yes. Should you do it? Probably not.

Using table prefixes, you can run two completely separate sites with table names like "site1_node" and "site2_node", so they don't collide. In your case, it sounds like maybe you also want to share data between the sites?

On solution to that, is to share tables between these two, but I strongly recommend against that. I've tried it on two different sites, and I've mostly gotten bit badly by it. Use Domain instead, to run two domains from a single Drupal install.


What permission gives users access to the "additional settings" options (author, etc.)?

Administer nodes is the permission for changing the author.


The Drupal 7 database layer uses PDO which prior to PHP 5.3.7 did not support MySQL with SSL.

Assuming you're using PHP 5.3.7 or later there is a patch available for Drupal to allow "arbitrary PDO options" to be used, which would include the ability to specify an SSL option.

See this discussion for a fair bit more information and links to the issues on php.net.

EDIT

For Drupal 6 you can change the mysql_connect() line in includes/database.mysql.inc to:

$connection = @mysql_connect($url['host'], $url['user'], $url['pass'], TRUE, MYSQL_CLIENT_SSL);

Although you should really turn this into a patch and apply it to the includes/database.mysql.inc file as hacking core is never a good idea.


As of Drupal 7, MySQL, PostgreSQL, and SQLite data types are supported in Drupal core.

Any web hosting company will offer at least one database server.

Basically:

you will copy the drupal files to your server via an FTP client
you will create a database from your web hosting company admin panel
you will go to www.yourwebsite.com/install.php and while installing Drupal you will provide the database credentials
done

You can find more info about creating your database here:

https://www.drupal.org/docs/7/installing-drupal-7/step-2-create-the-database


Checking site performance on remote vs. locally

a: Make your settings the same as your production system.

b: Performance measurements are only meaningful if you compare apples to apples. Your test environment needs to match your production environment - same cpus, same ram, same everything. A dev workstation rarely performs the same way as a web server. It's better to have a duplicate of your production system to use for testing / staging. i.e. if you were using amazon, you'd want second ec2 instance that matches your production system.


Modify user profile page, not login page

For theming user profile page use page--user--%.tpl.php template file.

To see all possible template suggestions right in your code you can enable Theme debug mode in sites/default/settings.php:

$conf['theme_debug'] = TRUE;


How can I rename a menu machine name in drupal 8

I also faced the problem when I needed to rename the machine name of my custom menus. In my case, I needed to remove hyphens in the machine name (this is a known issue https://www.drupal.org/project/drupal/issues/1353064), because some modules don't support hyphens. How I fixed it:

First of all you need to update already existing menu items (bundle, name, parent and etc.) I did it directly in a database through hook_update in your_custom_module:

function your_custom_module_update_8008() {
  $database = \Drupal::database();

  $menus = [
    'example-menu-machine-name-1' => 'examplemenumachinename1',
    'example-menu-machine-name-2' => 'examplemenumachinename2',
  ];

  foreach ($menus as $old_machine_name => $new_machine_name) {
    $database->update('menu_link_content')
      ->expression('bundle', "REPLACE(bundle, :old_value, :new_value)", [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->execute();
    $database->update('menu_link_content_data')
      ->expression('menu_name', "REPLACE(menu_name, :old_value, :new_value)", [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->expression('bundle', "REPLACE(bundle, :old_value, :new_value)", [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->execute();

    $database->update('menu_tree')
      ->expression('menu_name', 'REPLACE(menu_name, :old_value, :new_value)', [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->expression('id', 'REPLACE(id, :old_value, :new_value)', [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->expression('parent', 'REPLACE(parent, :old_value, :new_value)', [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->execute();
  }
}

Rename these names in configs. Your IDE should help with this. Don't forget also about renaming files for configs. For example:
system.menu.example-menu-machine-name-1.yml to system.menu.examplemenumachinename1.yml

If you have custom templates for menus also rename them:
menu--example-menu-machine-name-1.html.twig to menu--examplemenumachinename1.html.twig

Adjust classes in CSS|SCSS files, because they will be changed after renaming. Use IDE for this, it will save time :)

Run your build process locally and check results.

Take the dump of the database from the production and run a build with this database locally. Please compare menus between the local version and the production on the frontend.


Field values of nodes available as tokens

Have you looked at the Token API? With the API one can define custom tokens. The functions you should look at are:

hook_token_info()
hook_tokens()

With hook_token_info() you define new tokens. In your case you could retrieve all nodes of your configureation node type (with an EntityFieldQuery for example), loop over the entries and create a token for each of them.

In hook tokens you define what your tokens are replaced with - just load the node entity for the given token and retrieve the content of your value field.

Here is a tutorial I found useful when writing some custom tokens a while back: http://www.fredparke.com/blog/create-your-own-tokens-drupal-7


Variable name is "images_style" in your case


I don't think you can, not out of the box at least, but there's no reason to. Just use a static var, it will mean the API is contacted only once per request:

function getTitle() {
  static $title = '';

  if (!strlen($title)) {
    $title = $this->getTitleFromAPI();
  }

  return $title;
}


Overriding system.site.uuid with an environment variable

In the end, it was a matter of getting Drush to work on the remote environment.

I was also able to build a small module to update the site UUID of an existing site, however we didn't end up using it. The code for that is available at this repository.

Essentially, this boils down to running something like this:

\Drupal::configFactory()
    ->getEditable('system.site')
    ->set('uuid', $uuid)
    ->save(TRUE);

Where $uuid is whatever the UUID you want, whether this is generated manually or loaded from a service.


Drupal multisite configuration with a single database and redirection based on IP

If you are using IP2Local and purely redirecting to completely independent url that has a directly associated database (users, content, configurations) you don't really need domain access. You could keep all the data in the same database (save time on table maintenance) and separate them with prefix's.

You will need domain access if you are centrally sharing content, users and admin tasks as well as the database but need to open or restrict access based on the domain that the user is accessing through. If your users need to cross from site1 to site2 or access common content, this would be the way to go. Domain gives you more flexibility and scalability that option 1 but may require a little more work to set up.