Address field module autofill city and state when zip code is entered

Here is Javascript code that uses zipcodeapi.com API:

<script type="text/javascript">//<![CDATA[
$(function() {
    // IMPORTANT: Fill in your client key
    var clientKey = "js-9qZHzu2Flc59Eq5rx10JdKERovBlJp3TQ3ApyC4TOa3tA8U7aVRnFwf41RpLgtE7";

    var cache = {};
    var container = $("#example1");
    var errorDiv = container.find("div.text-error");

    /** Handle successful response */
    function handleResp(data)
    {
        // Check for error
        if (data.error_msg)
            errorDiv.text(data.error_msg);
        else if ("city" in data)
        {
            // Set city and state
            container.find("input[name='city']").val(data.city);
            container.find("input[name='state']").val(data.state);
        }
    }

    // Set up event handlers
    container.find("input[name='zipcode']").on("keyup change", function() {
        // Get zip code
        var zipcode = $(this).val().substring(0, 5);
        if (zipcode.length == 5 && /^[0-9]+$/.test(zipcode))
        {
            // Clear error
            errorDiv.empty();

            // Check cache
            if (zipcode in cache)
            {
                handleResp(cache[zipcode]);
            }
            else
            {
                // Build url
                var url = "http://www.zipcodeapi.com/rest/"+clientKey+"/info.json/" + zipcode + "/radians";

                // Make AJAX request
                $.ajax({
                    "url": url,
                    "dataType": "json"
                }).done(function(data) {
                    handleResp(data);

                    // Store in cache
                    cache[zipcode] = data;
                }).fail(function(data) {
                    if (data.responseText && (json = $.parseJSON(data.responseText)))
                    {
                        // Store in cache
                        cache[zipcode] = json;

                        // Check for error
                        if (json.error_msg)
                            errorDiv.text(json.error_msg);
                    }
                    else
                        errorDiv.text('Request failed.');
                });
            }
        }
    }).trigger("change");
});

//]]>

You can see an example here - http://www.zipcodeapi.com/Examples#example1

Since the question is how to autofill a valid city and state based on the user entering a zipcode first, the above Javascript code does that. Click on the example above to see how it works.


How to conditionally change email content from Webform submissions

This is more of a coding solution but you could implement hook_webform_submission_presave() in a custom module and use that to save the appropriate text to a hidden webform field type, then see if the token for that field will work in the email.

Alternatively, you could implement hook_webform_submission_insert() and send the email programmatically there, which would give you full conditional control of the email recipients and contents.


Creating section with static image and text with dynamic link

Found a way around - To use it as a view with some static content, create a label for a field in the view and style in template file.


Very slow loading on localhost (via. Uniform Server)

Well, for when I did run Windows last time with a webserver on it, I used Xampp, and it wasn't too slow out of the box. I found I still had to change portions of my.cnf to get it to run at a decent pace.

Several installs and jumps between Linux and Windows has made me realise that most of the Windows stacks I've come across have a lot to be desired performance wise and fiddling with my.cnf yields the best improvement.

Currently I use a 9 year old pc for most dev work, running Ubuntu server. It was painfully slow, but setting up MySQL caching to be a bit more reasonable and installing APC now has it running much, much faster than my quad core (with Xampp, admittedly no apc) at a mere 3 years of age. (The server only has 768mb of RAM).

My suggestion is to dive into my.cnf, though back it up first because if you get it set up wrong it may run much slower.

Alternatively get yourself set up with an Ubuntu server, made my life much easier (Though be prepared to lose several hours, maybe more if you are adverse to using a terminal) The Ubuntu Server guide walks you through pretty much everything you will need to do though.

As a disclaimer I have never used Uniform.

Edit from here on:

Relevant settings I use for my.cnf are:

[myslqd]
key_buffer              = 16M
max_allowed_packet      = 16M
thread_stack            = 192K
thread_cache_size       = 8
# I keep this low to limit max memory usage, with 2 or less people we don't get near this
max_connections         = 50
# table_cache is quite large compared to default because of the massive amount of tables
# Drupal uses.
table_cache             = 512
# Increased for those large queries, though keep an eye on these queries exceeding this
# value on your production server/hosting.
query_cache_limit       = 3M
# Greatly increased due to the large numbers of queries Drupal does.
query_cache_size        = 32M
# Total size of InnoDB's buffer, larger is better, I keep it larger than the DB of the
# of the site I am currently working on.
innodb_buffer_pool_size = 128M
# This stops InnoDB flushing its log at every transaction, instead flushiong it once
# per second. Can be detrimental to the last 1 or 2 seconds of data in case of a crash.
# Imo provides the largest boost on desktops due to their usually limited I/O capacity.
innodb_flush_log_at_trx_commit = 2

I no longer use myisam tables so I haven't played with myisam specific settings in there.

Overall the biggest bottleneck is hard drive access time so I keep as much in memory as possible, my dev server (Which is that ancient desktop box) has PATA drives so even writing to its miserable 8MB cache is slow. If your computer is low on I/O you need more caching, APC also makes a big difference in these cases.

Just keep in mind that you should compare the production environment settings to your dev ones to make sure that you stay within the production environment capabilities, though even on shared hosting with dismal caching and no APC, the presence of RAID usually makes up for it (Granted though that the host we use currently is the fastest one we have used, and some shared hosts are going to be slow no matter what you do.).

Also look at http://www.mysqlperformanceblog.com/ but also maybe avoid it because that is more geared towards dedicated database servers with obese amounts of RAM.


Specifically for taxonomy terms you have taxonomy_term_load(), e.g.

if ($field_items = field_get_items('node', $node, 'field_category')) {
  $tid = $field_items[0]['tid'];
  $term = taxonomy_term_load($tid);
}


I was logged out. Yes I tried to add field relationship on views settings, but my joined table was not shown. Consider that I want to join from a view showing my table to the users_field_data table, not vice versa.

my view is simply showing the the fields from my custom table. This works. But I can't add a relationship to the second db.
The SQL query is

SELECT my_tracking.id AS id, my_tracking.uid AS my_tracking_uid, my_tracking.event_id AS my_tracking_event_id
FROM {my_tracking} my_tracking
ORDER BY id ASC
LIMIT 25 OFFSET 0

my hook_views_data looks like

$data['my_tracking']['table']['name'] = 'event_tracking' . '.my_tracking';

$data['my_tracking']['table']['group'] = t('Event Tracker');

$data['my_tracking']['table']['base'] = array(
  'field' => 'id',
  'title' => t('Event Tracker'),
  'help'  => t('Contains data about tracking events.'),
  'database' => 'event_tracking',
);

$data['my_tracking']['table']['join'] = array(
  'users_field_data' => array(
    'table' => 'default' . '.users_field_data',
    'left_field' => 'uid',
    'field'      => 'uid',
  ),
);

$data['my_tracking']['table']['provider'] = 'my_tracking';

$data['my_tracking']['id'] = array(
  'title' => t('Record ID'),
  'field' => array(
    'id' => 'numeric',
  ),
  'sort' => array(
    'id' => 'standard',
  ),
  'filter' => array(
    'title' => t('Record ID'),
    'id' => 'numeric',
  ),
  'argument' => array(
    'id' => 'numberic',
  ),
);

$data['my_tracking']['uid'] = array(
  'title' => t('UID'),
  'help'  => t("The user's UID."),
  'field' => array(
    'id' => 'numeric',
  ),
  'sort' => array(
    'id' => 'standard',
  ),
  'filter' => array(
    'title' => t('UID'),
    'id' => 'numeric',
  ),
  /*  'relationship' => array(
    'title'              => t('User who is tracked'),
    'help'               => t('The user associated with the record.'),
    'id'                 => 'standard',
    'base'               => 'users_field_data',
    'base field'         => 'uid',
    'field'              => 'uid',
    'label'              => t('The who is tracked'),
  ),*/
  'argument' => array(
    'id' => 'numeric',
  ),
);

$data['my_tracking']['event_id'] = array(
  'title' => t('Event ID'),
  'field' => array(
    'id' => 'numeric',
  ),
  'sort' => array(
    'id' => 'standard',
  ),
  'filter' => array(
    'title' => t('Event ID'),
    'id' => 'numeric',
  ),
  'argument' => array(
    'id' => 'numberic',
  ),
);

No relationship can be added in views. Previously when I used a single database I was able to add the relationship by using the relatationship handler that is commented out above now. I don't know how to adapt it to 2 databases.


http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/watchdog/6 talks about the watchdog() call, and you access the reports it generates from admin/reports/dblog provided that you've turned on the optional Database Logging core module (dblog).


You can remove the rendering, you don't need it:

$the_view = views_embed_view('images', 'page_1');
$form['newthing'] = $the_view;

In fact, you should not render yourself in D8. And if you have the rare case you need to do this, read this first:

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


Drupal 7, login, "form_build_id" not used?

As drupal_prepare_form() notes:

  The form_build_id is used as key to cache a particular build of the
  form. For multi-step forms, this allows the user to go back to an
  earlier build, make changes, and re-submit.

More than anything else, form_build_id is for maintaining the form state through page requests. As you can see in some of the core processing functions (e.g. drupal_build_form(), drupal_rebuild_form(), & drupal_process_form()), form_build_id isn't required for form processing.

In some instances (e.g. multi-step forms) breaking the form_build_id would break the behavior of the form since there is previous data to retrieve, but for the login form there's no state needed to be preserved.


Calling entity reference field in page template

The entity reference field normally contains just the entity ID as value.

Looking at Twig get value of field in entity reference and Drupal 8 loop entity reference fields.twig it seems a bit that

{{ node.field_name.entity }}

or

{{ node.field_name.0.entity }}

or

{{ node.field_name[0].entity }}

might work.

If it doesn't work, try Twig Tweak which gives you some handy functions to print Drupal entities in Twig.

{% set nid = node.field_name.target_id %}
{{ drupal_entity('node', nid) }}

Or even easier as recommended by @4k4 in the comments:

{{ drupal_field('field_name', 'node') }}

  Twig Tweak is a small module which provides a Twig extension with some
  useful functions and filters that can improve development experience.


Content Access has "Per content node access control settings" available for each content type.

If you navigate to the "Access control" tab for your content type (or navigate to admin/structure/types/manage/content_type/access) you should see the following fieldset:

As the description suggests, once you've enabled that setting each piece of content of that content type will have an 'Access Control' tab. From there you can decide which roles should be able to access that individual piece of content.

This is what the 'Access Control' tab looks like once you've enabled that setting:


How to display comment status with radio buttons?

I think you have to use rate module for your comment, then use Rules module to close the comment on specific node.


I had the same problem and very simple solution for it I found just need in output write

 print render($data->field_field_artengalerie_term_bild);

always my solutions is shortest ;)


Importing 'alt' and 'title' fields does not work for custom image migration

You're only mapping the fid there - you need to also map the alt and title for them to come over:

field_galerie:
  plugin: iterator
  source: field_galerie
  process:
    target_id:
      plugin: migration
      migration: luxus_files
      source: fid
    alt: alt
    title: title


A way to share content structure across several panel pages

Why not use mini panels, one of the sub-modules of Panels.  Mini-panels are just like panel pages except that instead of taking a path and acting like a page they act like blocks.  They are specifically designed to be embedded in other panels/pages.

So you can make a mini panel called sidebar and then if you ever have to make a change just update it in one place.


Installing SMTP module, not able to enable module

Most likely, your host provider does not have one or more of the PhP extensions enabled for your site.  Check the status page / php info to see if the following items listed in the readme are there:

  REQUIREMENTS

  Access to an SMTP server
  The following PHP extensions need to be installed: ereg, hash, date & pcre.
  Optional: To connect to an SMTP server using SSL, you need to have the   openssl package installed on your server, and your webserver and
  PHP   installation need to have additional components installed and
  configured.

If the requirements are there, check the watchdog error log (you probably have).

If possible, check the actual server error logs.

If you can't check the error logs, you might try going to the Logging and Error settings in the Devel area and setting the option to display all errors with a stacklog.

NOTE: This should be reset once your debugging is done.


Here is my take on it

Views

First and most basic advantage is it has a UI which makes it easier for beginners and people with not much knowledge php of to fetch data and display it just with a few clicks.
You can apply filters and relationships to make any kind of joins and filtration of data just with a few clicks.
It provides easy access to exposed filters which allows you do do sorting of data.
It has ajax support.
It has a built in cache mechanism to cache data.
You can AND or OR your data just by drag and drop.
It has support to display the data in various formats like grid, table etc which are available just at a click.

These are just a few points. Now if you try and compare these points to writing a PDO query then yes PDO is definitely fast but you forget after getting the data you also have to do the processing to display the data. Now if you try and do the above mentioned points in a custom module I am pretty sure you will run over a 500 lines of code to implement most of the features.Also don't forget the custom code which needs to be maintained.

If you want to compare views to a PDO check the views query time and the PDO query time it will not be a major difference. Views takes time to do all the rest of the fancy stuff you need to process sanitize your data and display your data in the format of your choice which takes time.

If you are comfortable with PDO I would definitely recommend you to go ahead and use it. The adv are you are using a core feature, 1 less module to me loaded so less http request to load the js and css files.

UPDATE: 10/03/2012
Also came across this node on drupal.org: http://drupal.org/node/242311


How do I restrict a user from edit his/her own profile

You can either hide them from the form on the Manage Form tab, or use a form alter hook to set #access to FALSE if they don't fit a certain role.

You can also try the Field Permissions module.


How do I relocate the "Reset password" form?

How do I print the local task bar in different places depending on the base route? is about changing where the tabs for local tasks are rendered in the page. It's different from what you want to achieve.

The module you found (No Request New Password) is for removing the Request new password link from block and user page. This is probably part of the task you want to achieve, but you cannot use that module because it has not been completely ported to Drupal 8, and it would not work. If you look at the content of the noreqnewpass.module file, you will notice it is using functions that don't exist anymore in Drupal 8, as in the following hook implementation.

function noreqnewpass_form_alter(&$form, $form_state, $form_id) {
  if (($form_id == 'user_login_block' || $form_id == 'user_login') && variable_get('noreqnewpass_disabled', true)) {
    $key = array_search('user_login_final_validate', $form['#validate']);
    $form['#validate'][$key] = 'noreqnewpass_user_login_final_validate';
  }
}

The task you want to achieve requires to:

Remove the Reset your password local task from the /user/login page
Change the path associated with the user.pass route
(Eventually) remove the Reset your password link that appears in the login block

The fist step requires a module implementing the following hook.

function custom_menu_local_tasks_alter(&$data, $route_name) {
  // Remove the "Reset your password" tab only from the login page.
  if ($route_name == 'user.login') {
    unset($data['tabs']['0']['user.pass']);
  }
}

The second step requires altering a route another module defines. There isn't any hook to do the task, which requires writing code for an event subscriber. Fortunately, Drupal 8 has a class that can be extended to do the task.

class CustomSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Change path '/user/password' to '/hidden/user/reset'.
    if ($route = $collection->get('user.pass')) {
      $route->setPath('/hidden/user/reset');
    }
  }

}

An event subscriber is a service using the event_subscriber tag. This means it needs to be defined in the .services.yml file of the module.

For the last step, it's sufficient to alter the login block.

function custom_block_view_user_login_block_alter(array &$build, BlockPluginInterface $block) {
 unset($build['user_links']['#items']['request_password']);
}


I see two options to achieves this.

The first one is to alter the page callback for the taxonomy/term/%taxonomy_term path through an implementation of hook_menu_alter. In the custom page callback, when displaying a term from your vocabulary, use drupal_goto() to redirect to the search page. And for terms in other vocabularies, you can re-use taxonomy_term_page() to preserve the original behavior.

The second option is to implement hook_entity_info_alter() to alter the uri callback of the taxonomy term entity type. In the custom URI callback, when getting the URI for a term of your vocabulary, returns the URI of the search page. For terms in other vocabularies, you can re-use taxonomy_term_uri() to preserve the original behavior.


Is there a way to load content of each tab in the view using AJAX?

I had a similar problem. The following code worked perfectly for me.

jQuery(".quicktabs-wrapper ul a").click(function(e) {
    e.preventDefault();
    jQuery(this).parents('.quicktabs-wrapper').find('.quicktabs_main  .quicktabs-tabpage').addClass('quicktabs-hide');
    showId = jQuery(this).attr('id').replace("-tab-", "-tabpage-");
    jQuery('#' + showId).removeClass('quicktabs-hide');
    jQuery(this).parent().siblings('li').removeClass('active');
    jQuery(this).parent().addClass('active');
  });


The fields you are looking for are under '#item', for example:

 {{ item.content['#item'].title }}

To set variables for twig put a theme_preprocess_field() function in  MYTHEME.theme.

To examine variables use kint (this is in the devel module):

{{ kint() }}
{{ kint(items) }}


Is there any way to export user account information and content profile together?

I would still go with Views, unless you want to do it in your own custom module as suggested in the other answer.

There is Profile CSV, but this is limited to user accounts and core profile fields. There was a feature request for Content profile, but that issue wasn't finished, and in fact a Views-based approach was also suggested in that thread.

You can build a view of user account fields and related CCK views using Views relations, and export to CSV using the Views data export plugin. (And you can later import CSV via User import).

I believe any solution other than Views requires coding.


How do I hide text format options in node view with in place editing?

You can find multiple questions/answers to this problem in this site... One of the most recommeded approach is using hook_form_alter hook: example:

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

  // dpm($form);
  // dpm($form_id);

  if($form_id == 'MY_NODE_FORM_ID') {
    $form['#after_build'][] = 'custom_my_node_form_after_build';
  }
}

function custom_my_node_form_after_build($form) {
  // dpm($form);
  // Find the right field's format option with dpm() function

  $form['MY_FIELD']['und']['0']['format']['#access'] = FALSE;
  return $form;
}


You can reset it directly in the db, if you have access to it?

UPDATE users SET PASS = md5('new_pass') WHERE uid = 1


This paragraph in hook_node_load() docs page explains it in details:

  This hook is invoked during node loading, which is handled by entity_load(), via classes NodeController and DrupalDefaultEntityController. After the node information is read from the database or the entity cache, hook_load() is invoked on the node's content type module, then field_attach_load_revision() or field_attach_load() is called, then hook_entity_load() is invoked on all implementing modules, and finally hook_node_load() is invoked on all implementing modules.

Here's the breakdown, from first to last call:

entity_load()
hook_load()
field_attach_load_revision() or field_attach_load()
hook_entity_load()
hook_node_load()

What this means to you is that using a different hook you will be able to modify values earlier or later. This matters if you're overriding value from another module for example. Otherwise, I think it's safe to use either.


You have to change the name of your template file to user--login.tpl.php, place this file in the templates folder of camuse theme and clear all caches.


A referenced node is missing--when did it disappear?

Drupal 7 does not delete references to deleted nodes by default. See the Field reference delete module. Some details about it, from its project page (check that page for even more details):

  This module removes references to a deleted entity from fields stored in an SQL database. It exists to prevent stale references to non-existent content from causing unexpected problems (for example, when the referencing content is being displayed).

I'm not sure if it will clean up existing "dead" references, but at least moving forward it does.


View block filter by taxonomy term (field)

What is the criteria according to which the two different blocks will "know" whether you want to show cars or trucks?

If you want to control this, and have two separate Blocks showing different term-related content, you can create two Blocks but add regular Filters to them, filtering to show content related to either cars or trucks. The add each separate Block where you want them in a theme region.

If you want an automatic solution where a contextual filter does everything, you usually want to show either cars or trucks, but not both on the same page. Contextual filter will "sense" the context, it will recognize something on the page you're currently viewing, and where you placed the Block, and it will pass this context info to your Views, and filter results according to it. This is commonly used to place Blocks on Node pages, where you want to show other content that has been tagged with the same term. For example you're viewing Car1 node, and want the Block to list all the other nodes that have also been tagged with the term "car", so you would see Car2, Car3 etc. Besides the Contextual filter to pull the related content, you will also want the second contextual filter that would exclude the current node from the list, because it doesn't make sense to the visitor to see it there. You will need to adjust Contextual settings when placing the Block in a theme region.

The third option may sound the closest fitting to your description: Create One Block listing all nodes of that type, add the Field for the Taxonomy reference field, and under Format use the Taxonomy reference field to "Grouping field Nr.1". This will list all content but it will be Grouped in clusters based on the "car" or "truck" tags. You can edit the Field and "Exclude from display" because you will see it in the group title. There is no need for Contextual filters here as you want to list everything, you only want it separate into groups. Place the Block in a theme region and adjust visibility...

You can add the same Block to display in Drupal as many times as you want, in the same theme region, or in a different place, but you can't make it behave differently. A Block with a Contextual filter can show different results only if the Context it's surrounded with is different. But if on the same page, the context is the same, and the result will be the same.

BTW the "Vehicle type" is a Taxonomy Vocabulary, and the "car" is a Taxonomy Term.


Split node edit tab in several tabs with panels (or programmatically)

It sounds like you have done a lot of work already, and this continues to be a learning experience.  Since the form is now managed how you want it and it is only the data management in the save process that is causing you trouble, I would suggest a few code additions.  Using hook_form_ID_alter there are two methods you can try.

Method 1 Add a custom validation callback to the form.

$form['#validate'][] = 'MYMODULE_node_data_validate';

Then in your new validation function I suggest loading the node ($node = node_load(nid);) and propagating the data into the form_state.  I am not sure this will work, but I have it listed as method 1 because it is the less disruptive path of the two that I have in mind at the moment.

Method 2 Replace the submit handler with your own.  Similar to the validate function mentioned above, the idea here is to load the node to get the data that was not present on the form that you edited.  However, this time you are going to invoke node_save yourself.  Also you will need to end with a drupal_goto or some other method of sending the user someplace.  Yes you could add an additional handler to the #submit array in the form variable, but either it will be too late to prevent the change the form is doing or it would just be a different name for method 1.

function hook_form_ID_alter(&$form, &$form_state, $form_id) {
    $form['#submit'] = array( 'hook_something_submit');
}
/**
 * Implements hook_form_FORM_ID_alter();
 */
function vts_nodedit_form_accompagn__node_form_alter(&$form, &$form_state, $form_id) {
    $form['#submit'] = array( 'vts_nodedit_data_submit');
}

function vts_nodedit_data_submit($form, &$form_state) {
  // possible cause of missing data is that the form build populates
  $original = node_load( $form_state['node']->nid );

  // this drupal core function does the work of a full node edit save
  // but we have to have the node to hand it
  // and I do not trust all of $form['node'] in your instance
  field_attach_submit('node', $original, $form, $form_state);

  drupal_set_message(t('The changes have been saved.'));

  if( isset( $form_state['redirect']) ){
    drupal_goto( $form_state['redirect'] );
  } else {
    drupal_goto( '/home' );
  }
}

EDIT
The difference between form_state['input'] and form_state['values'] is that input is the raw $_POST from the user.  I think it would be a security concern to use that directly.  The other validators that are running (why we use $form['#validate'][] and append instead of replace) are taking the new data from input, cleaning it, and putting it in values.  Then if there are blank spots, they fill values with #default_value of the node.  Default is typically the existing value.  Therefore, a submit handler can ignore form_state[input] and have the benefits of drupal in just the form_state[values] array.
Input vs Values


Changing a template using user role and publishing variables

change code

  $variables['template_file'] = 'node__article2';

to

  $variables['theme_hook_suggestions'][] = 'node__article2';


Try drush status and drush help to see if Drush is working with your Drupal 8 site.  Presumably, drush help will confirm that the migrate-status command is not available.  Try enabling the migrate module on your Drupal 8 site.


You can use Pathauto module and follow these steps:

Enable pathauto module
Go to admin/config/search/path/patterns and set the patterns for specific taxonomy using Token module and save the form
Go to admin/config/search/path/update_bulk and generate URLs for taxonomy

Don't worry about the existing URLs (no matter wherever you added it) it will remain same, Pathauto will not effect anything. Now, visitors can access by both URLs (default and newly generated).

I hope this will help you.


Embed a node form with default values in drupal 7

If you are using a 'select list' widget for the node reference you can do this:

$form = node_add('product_plan');
$form['FIELD_NAME'][$form['language']['#value']]['#value'] = 'NID';
return drupal_render($form);

'autocomplete' widget would look like:

$form = node_add('product_plan');
$element['#default_value'] = 'NID';
$form['FIELD_NAME'][$form['language']['#value']][0]['nid']['#value'] = node_reference_autocomplete_value($element, FALSE, '');
return drupal_render($form);


How to list all nodes of nodetype A which has the current node referenced?

Simplest way would be to make references two-way. To do this, use:

Corresponding Entity References for Drupal 7
Corresponding node references for Drupal 6

That way, current node will reference all nodes that reference it - and from this point creating a view is trivial - or you can simply display the field created for back reference, without need for a views module at all.

Other way is to use Views. Create a view displaying nodes from content type A, add argument content reference field > provide default argument > node ID from URL and display this block view on the nodes from content type B.


You may need to do some research into the way the drupal system works. Here is the documentation page for how to theme drupal. http://drupal.org/documentation/theme

If you are looking to create you own theme. For a beginner, it may be easier to start with a theme framework to mold it into what you want. Here are 3 of some of the more popular frameworks; Zen, Fusion, and Adaptive Theme.

P.S. - You may want to consider doing some basic google research prior to asking questions on here without more supportive information.


You can also use the rules module. You can add a rule which does a redirection after successfull login.


Rule to check specific field of content every week

A possible solution is to transform the rule you already have, into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg X secs or mins "after saving the content") ... That Rules Component will then be executed next time cron runs.

If you then also add an extra Rules Action in that Rules Component (as last Rules Action) to reschedule the same Rules Component after 1 week, you should have achieved what your question is about.

Obviously, as soon as at least 1 of the Rules Conditions in your Rules Component are no longer satisfied, its Rules Actions will not be performed anymore, so that is when the weekly rescheduling also stops.

Easy, no?


You could still use floors as numeric field, having numbers as keys and display output as needed.

Example of "List (integer)" values:

-1|Basement
0|Ground floor
1|1
2|2
3|3
100|Attic

This would allow you the same logic for floors.

EDIT:
When selecting the field as a filter in Views you need to choose the delta value. It looks something like Content: Floors (field_floors:delta). This will give you the integer filter options such as Is greater than or equal to.


Compared the facet definitions via Dev module and noted the " Transform entity ID to label" option.  That does it.


Why is it sometimes $node->field_name[0], and sometimes $node->field_name['und'][0]?

The lack of the 'und', or LANGUAGE_NONE level data seems to indicate that the field has lost the ability to be translated. I've never encountered such a field.

field_get_items() as already pointed out is the canonical way to safely retrieve field data. Any fields that don't work with field_get_items should be considered broken.

I would hazard a guess that you either

Have a broken contrib module that re-arranges field data and doesn't know better than to sometimes remove the language level.
Your field settings have just broken somewhere along the way. Potentially because of a reason similar to above.

Does the problem keep happening on newly created fields?

Can you reproduce on a clean install?


Check  Administrator -> Configuration -> Media -> File System to personalize your tmp path. Make sure to use relative paths and have the right privileges for the Apache user.

I personally like this article fix file upload. He has good observations. It worked for me.

Recently, I downloaded my site to my Mac computer. It happens that in my Mac I was using mod_userdir for Apache and I forgot that in /etc/apache2/users/nameofuser.conf I need to set AllowOverride All, otherwise I will have the following message:

  The specified file temporary could not be copied because the destination directory is not properly configured.


What is the warning I get after moving to a new server?

Check for file permission where this module is trying to write , especially the temporary folder: admin/config/media/file-system


How to implement a Rules Action to loop through quantity of a products bought?

Consider this Rules Component (in Rules export format, use the Rules UI to import it in your own site):

{ "rules_grant_user_points_multiple_times" : {
    "LABEL" : "Grant user points multiple times",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "userpoints_rules" ],
    "USES VARIABLES" : {
      "points_to_grant" : { "label" : "Points to grant", "type" : "integer" },
      "quantity" : { "label" : "Quantity", "type" : "integer" }
    },
    "DO" : [
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "points-to-grant" ],
            "op" : "*",
            "input_2" : [ "quantity" ]
          },
          "PROVIDE" : { "result" : { "calculated_points" : "Calculated points" } }
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "site:current-user" ],
          "points" : [ "calculated-points" ],
          "tid" : "0",
          "entity" : [ "site:current-user" ],
          "operation" : "Insert",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

Some more details about this Rules Component:

It uses 2 parameters (both "integer"), i.e.:

Points to grant, which is like your custom field named “points”.
Quantity, which is like your quantity of the products sold.

Rules Actions:

Calculate a new variable (= calculated_points), which is simply a multiplication of the above 2 parameters.
Grant user points for an amount equal to ... euh ... indeed: calculated_points (adapt the details of the actual transaction to fit your needs).

These User Points will be granted to the "current user". Optionally you could just make that yet another parameter for the Rules Component also. I.e. if "current user" is not the customer who bought the quantity of products (which would allow one customer to buy such points for another user should you want to allow that, similar to a gift-card).

With that, all that's left is to finds the right spot in your existing Rules logic (related to checkout), to use the above Rules Component.

Easy, no?


Dependency injection for FormElement #process callback

Dependency injection for any method of a class is done for the whole class. So if you have a dependency for the method you're adding for any method in the class, you will set that as a dependency for the whole class, not just a single function. However, #process callbacks are static functions, and static functions cannot use dependency injection. They should use the \Drupal::service() method, which is for static functions and procedural code.


@IgorTengab
An entity in Drupal 8 needs translation to be enabled to be translatable

For example by going to /admin/structure/types/manage/ENTITYNAME > language settings > enable translation

For more info look here

But for your purpose perhaps a light-weight alternative would be to create a custom entity https://www.drupal.org/docs/8/api/entity-api/create-a-custom-content-entity


It seems like AMAZON Payments module is not available for Drupal 7. No discussion about D7 port also happening.

If you are interested in writing D7 port for commerce module below article will help you.

http://www.drupalcommerce.org/developer-guide/utilizing-core-apis/writing-payment-method-module


Creating a view that excludes entity referenced nodes

Views Reference Filter might help you:

  This module provides the feature missing in Views module - subquery filter for IN (NOT IN) condition, such as (quite informal):

  SELECT n.title FROM node n WHERE n.nid [IN | NOT IN] (SELECT n2.nid FROM node n2 WHERE ...)

  or

  SELECT n.title FROM node n WHERE n.node_reference_field [IN | NOT IN] (SELECT n2.nid FROM node n2 WHERE ...)


How to programmatically get list of available image styles

use

use Drupal\image\Entity\ImageStyle;

and load all image style with

$styles = ImageStyle::loadMultiple();

Also you can use  entity_load_multiple  with

 styles = \Drupal::entityTypeManager()->getStorage('image_style')->loadMultiple();


EntityQuery condition for multivalue fields

Try to use NOT IN instead of <>.

->condition("my_field", [\Drupal::currentUser()->id()], "NOT IN");

You can learn more here.


This is working as intended.

  I have a Basic Page with PHP code in it. In this PHP code, I have some "Print".

You should not have any PHP (not "print" or anything else) as part of the content of a node.  Drupal is designed to treat PHP in nodes as text, and will just output it verbatim. Anything else would create a huge security hole in your site.

Just delete those "print" statements, and they will no longer appear.


That hook wont' go away and its fine to use it. That warning was added a while ago, it's not possible to change it anymore in 8.x AFAIK. We hoped to do that before the stable release.

Name is a true field but it is a base field. You should be able to get the base field definitions from the entity type manager if it is not there, clone it and add your constraint.


How to programmatically build a page and a form in the same page

You must use the formBuilder, like this:

$render = [];
$render['elememt1'] = [
  '#type' => 'markup',
  '#markup' => t('Test'),
];
$render['element2'] = \Drupal::formBuilder()->getForm('Drupal\MY_MODULE\Form\MyFormClass');// The destination of your form.

return $render;


How can I replace the hyphens in front of child terms with something else?

Looks like there is no easy way to override them, they are added by TermSelection::getReferenceableEntities in core/modules/taxonomy/src/Plugin/EntityReferenceSelection/TermSelection.php:73:
$options[$vocabulary->id()][$term->id()] = str_repeat('-', $term->depth) . Html::escape($this->entityRepository->getTranslationFromContext($term)->label());

If you decide to edit it, I suggest using a Composer patch system afterwards if you are using Composer.


I have never used it in that way, but some thoughts:

The second link doesn't seem relevant, as I suppose that you use Views 3.

If you use the approach described in the first link, than you don't need to implement hook_form() in your module, instead you need to create a views field handler and there you need to define the methods views_form()and views_form_submit(), optionally also views_form_validate(). You would then "add the form to the view" using the Views UI where you can add the field (the one that you have written a handler for) to the display. That's  how your handler get's called and is responsible for the rendering of the element, which usually renders a value wrapped in some markup, but in your case it would render a form.

The first link explains that all very well. Just go through it again and try to follow it in detail.


The send function does not work in a custom form

You have to write the submit handler for the form to save data.

  /**
   * {@inheritDoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Insert queries.

    $query = \Drupal::database()->insert('mymodule_table');
    $query->fields([
      'name' => $form_state->getValue('name'),
      'tel' => $form_state->getValue('tel'),
    ]);
    $query->execute();

  }


How to add active class to title which is loaded via views in block

If you are generating a menu structure, I would suggest the following:

Your view should use the HTML List format.  In the settings use the unordered list type.  You probably should add a list class setting like nav (or your theme's default class for nav elements).

The Format Show type should be Fields.  In the settings, uncheck the "Provide default field wrapper..." option.

The results should be a straight forward ul list with li wrapped anchors.  E.g.

     Node Title

// other titles below

Standard menu CSS should work on this,  e.g .nav > li > a to select anchors and the like.

If you still need a css class on the label, you can add a hidden path field above the title.  Remove the link to content option.  Then rewrite the title field with something like:

{{ title }}

To get an active class, you have several options.

If you are using a bootstrap based theme, you can just add the appropriate bootstrap classes to this since it's a simple ul structure.  See the bootstratp docs for more details.

It is easy to add a bit of jQuery script to do this.  See this for some sample code.

Or you can do it with the template_preprocess_views_view_field() hook.  Here's some sample code for that.  You will probably have to dump the output value to see how it is layed out.  Note that you will have to play some games with getting the current path into the same format, especially if you are using path aliases.  Some sample code.


Update the author_uid for an entity registration

(a) hook_entity_presave() should work, giving you access to the entity, before it is persisted, e.g.:

/**
 * Implements hook_entity_presave().
 */
function registration_alterations_entity_presave($entity, $type) {
  if ($type === 'registration' && $entity->author_uid === 0)) {
    $entity->author_uid = variable_get('registration_alterations_anonymous_registrations_reassign_uid');
  }
}

(b) Alternatively, you could use hook_field_attach_submit(), which is also triggered inside registration_form_submit() and would give you access to the submitted form in case you needed it. This would look similar to (a):

/**
 * Implements hook_field_attach_submit().
 */
function registration_alterations_field_attach_submit($entity_type, $entity, $form, &$form_state) {
  if ($entity_type === 'registration' && $entity->author_uid === 0)) {
    $entity->author_uid = variable_get('registration_alterations_anonymous_registrations_reassign_uid');
  }
}

Good luck!


I don't believe there's a way to sort the values of a field at the view level. However, you can easily get the results you want by creating a custom field formatter and then using it to render your field in the view.
You can read more about field formatters by reading the Create a custom field formatter documentation on d.o.
Create a custom formatter that extends the formatter you're using now. I'm guessing you're using the default ERR formatter so you'll want to extend Drupal\entity_reference_revisions\Plugin\Field\FieldFormatter\EntityReferenceRevisionsEntityFormatter.
You'll need to override viewElements() or getEntitiesToView() - I'd override getEntitiesToView().
protected function getEntitiesToView(EntityReferenceFieldItemListInterface $items, $langcode) {
  // Let the parent class get all entities in the field first.
  $all_entities = parent::getEntitiesToView($items, $langcode);
  $my_entities = [];

  // Get first Description paragraph.
  $desc = $this->getFirstOfType($all_entities, 'MY_DESCRIPTION_BUNDLE');
  if (!empty($desc)) {
    $my_entities[] = $desc;
  }

  // Get first Image paragraph.
  $img = $this->getFirstOfType($all_entities, 'MY_IMAGE_BUNDLE');
  if (!empty($img)) {
    $my_entities[] = $img;
  }

  return $my_entities;
}

protected function getFirstOfBundle($entities, $bundle) {
  foreach($entities as $entity) {
    if ($entity->bundle() == $bundle) {
      return $entity;
    }
  }

  return FALSE;
}


Function to determine whether my Cart is empty?

Using the same technique as commerce_cart_block_view (thanks to Ryan Szrama for the assist!), you'll need to:

Get the order using commerce_cart_order_load, then check to see if there are no line items.
Apply the entity metadata wrapper to retrieve further wrappers for the entity properties
Count line items in the cart, filtering for products only

For the access callback itself, take a look at Do you have an example of hook_menu() access callback? for several examples and links to documentation.

Therefore, the callback should be something like:

function MODULE_access_check() {
  global $user;
  if ($order = commerce_cart_order_load($user->uid)) {
    $wrapper = entity_metadata_wrapper('commerce_order', $order);
    return commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types()) > 0;
  }
  return FALSE;
}


Always prompt for a shipping address even if there are no shippable products with Ubercart

The only work around for this is to alter the UPS module yourself or report it as bug, (because in my opinion, this is a bug.)

You could probably write a module that would override the UPS module to circumvent the above suggestions. You have pretty clearly hit the nail on the head though. The problem is not Ubercart but the modules that are interacting with it inappropriately. I know the FedEx module takes into account shipable products, if my memory serves me correctly.

The entire shipping pane should be hidden if there are no shipable items. (That is the point of having that option in the products.)


Display values of custom fields created on media entity in a template file

Your question is more about how to handle Drupal templates and passed variables. I suggest you to use Devel and Devel Kint modules to be able to debug variables just in your template like this:

{{ kint() }} - print all available variables

{{ kint(your_var_name) }} - print particular variable

And don't forget to enable twig debug mode - it will show you templates structure.

Once you have everything visible it becomes much easier to understand.


You can stop roles from editing menus via the permissions page. That should lock that down.

Then to manage the menus on all your sites you could use Menu Export/Import module (https://drupal.org/project/menu_import), which plays nicely with Drush to allow you to export/import entire menus. You could maintain your "master" menu in a text file in json format and then periodically push it out to all sites at once using Drush aliases or a simple shell script. Because Drush uses uid 1 I think you should be able to do whatever you need regardless of how you set your roles' permissions via the UI.


Can I change the Display Settings by modifying the database?

Export the config and change in node.type.[content-type].yml:

display_submitted: false

and import the config again or edit the live config directly with Drush, for example of the content type Article:

drush cedit node.type.article


How do you troubleshoot search tracking not working with the Google Analytics module?

You could try the GA debug chrome extension for troubleshooting this issue. It will give you better insight into what is being sent to GA from Drupal


Add print button in the "Review order" page

You can try using the PrintFriendly & PDF module, which has a version for Drupal 7 and one for Drupal 8. (The development snapshot for Drupal 8 has been created on July 27, 2017.)

The description of the module says:

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

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

Using this module you can add a print button to review order pages.


Workaround for: Message rejected due to DMARC policy for yahoo.com

You are correct in your update that:

This is a Drupal problem, in that the script must change how it sends emails.
What Drupal uses in the "from" field should actually be in the "reply-to" field.
This can be fixed using a hook. (Specifically, hook_mail_alter().)

If you don't want to write any code, I suggest you use the Contact Reply To module by rfay.

Alternatively, I wrote a more general-use module that I described here.

I use my solution on all of my sites and have not had any trouble yet.

Some of the other suggestions are incorrect, in that hook_mail() does not catch every email, and therefore is not appropriate, and you cannot use some of the other smtp solutions, because the "from" email address is not consistent (ie., it is provided by site visitors).


Searching for a user details (including custom fields) in People Administration Page

I recommend using Views.  With this you can create a searchable, sortable and filterable display using any format you desire, and including any fields you want.

  You need Views if

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


You can do this with Rules. Here is an example:

{
    "rules_auto_add_shipping_service" : {
      "LABEL" : "Auto-add shipping service",
      "PLUGIN" : "reaction rule",
      "OWNER" : "rules",
      "REQUIRES" : [ "rules", "commerce_order", "commerce_shipping", "entity" ],
      "ON" : { "commerce_order_update" : [] },
      "IF" : [
        { "data_is" : { "data" : [ "commerce-order:type" ], "value" : "commerce_order" } },
        { "commerce_order_contains_product" : {
            "commerce_order" : [ "commerce_order" ],
            "product_id" : "YOUR-SKU-HERE",
            "operator" : "\u003E=",
            "value" : "1"
          }
        }
      ],
      "DO" : [
        { "commerce_shipping_delete_shipping_line_items" : { "commerce_order" : [ "commerce_order" ] } },
        { "commerce_shipping_method_collect_rates" : {
            "shipping_method_name" : "flat_rate",
            "commerce_order" : [ "commerce_order" ]
          }
        },
        { "commerce_shipping_rate_apply" : {
            "commerce_order" : [ "commerce_order" ],
            "shipping_service_name" : [ "" ]
          }
        }
      ]
    }
}

Just change the SKU or the other conditions to suit your needs.


It has been a bug in Drupal, but should be corrected since Drupal version 7.13. See more details here: http://drupal.org/node/1234830

As a workaround, you can empty (truncate) the cache_menu table, since it is just a cache table and will be regenerated. Of cource, you'll have a trade-off in performance, in that case.


A EntityFieldQuery doesn't return fully loaded entities as result.
Try running the query result through entity_load('type', $result['type']). Then you can render the resulting entites through entity_view('type', $entities).

Here an example:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'article');
$result = $query->execute();
if (!empty($result)) {
  $entities = entity_load('node', array_keys($result['node']));
  return entity_view('node', $entities, 'full');
} else {
  return array('#markup' => t('No article nodes found.'));
}


You have to add this on the end of your endpoint URL:

?_format=FORMAT. So if you want JSON, its ?_format=json.

This is a new change in 8.5.0 requiring this argument, but I could not locate in the changelogs exactly why it is now required otherwise a 406 is returned.

This same thing happened to all my REST endpoints until I added that.


Does inactive modules can make my drupal site slower?

I don't understand Jance's response.  He says "it won't hurt", but then says these disabled modules are sucking up resources?

Saying inactive modules don't impact performance is not completely accurate... but it certainly is less important than the number of enabled modules.

While the hooks of an inactive module with code left in sites/all/modules aren't loaded when a specific form or page is loaded, all .info files from any code active or inactive are scanned when loading the admin/modules and admin/themes.  Drush also scans all directories for Drush related includes in profiles and sites... regardless of what's active.  Inactive modules aren't going to cause as much of a hit to CPU and memory as an enabled module, but having unused code in sites/all/modules isn't a good thing. Best practice would be to only install modules on a test site.  Never install a module on a live site just to test it.  Even when uninstalled, modules can leave a lot of cruft behind that can impact performance.

Modules that were once installed, but are now inactive could create tables and define variables add to the cruft at the database layer.  Even if you uninstall the module, the uninstall process relies on the developers who wrote the module to clean up after themselves.   Modules that use Features often leave even more cruft behind.  Disabling a Feature "module" does not remove the content types, taxonomies, fields, views, blocks, etc that it created.  Even uninstalling and deleting the code doesn't always clean up after a Feature.

I realize that not everyone can afford the type of dev -> test -> live workflow you get with a Drupal specific host like Acquia or Pantheon or has the technical skill to run a local version of their site, but if you don't have that type of testing environment be prudent about the modules you enable then uninstall.

Alas, hindsite is 20/20... for modules you've already enabled in the past that you've decided not to use, uninstall them and remove the code from sites/all any module.  This won't improve performance as much as reducing the number of modules enabled, but leaving this code certainly won't help performance or your ability to maintain the site.


How do I force a new module to inherit the file permissions the modules directory has, after update?

I know this is old but recently I stumble upon the same problem:

Site installed on IIS 8 under Windows Server 2012 R2
After updating with Drush core and modules, permissions of modules
and updated files get messed up.

Solution I found is:

right click on website folder> Security > Advanced
check: "Replace all child object permission entries with inheritable
permission entries from this object"
Apply

If files don't shows navigate to /sites/default/files or whenever files are stored and change permission to this folder and subfolders.


How to integrate Datatables in my Bootstrap theme (to make it match the look and feel of my site)?

Have a look at what is described in http://www.datatables.net/manual/styling/bootstrap . Here is a quote from that link:

Bootstrap is a CSS framework that lets you quickly and easily build a user interface that has a unified look and feel. The great news is that it is very easy to integrate Bootstrap and DataTables such that your fully featured DataTables will match the same look and feel of the rest of your site.
Bootstrap provides a number of options for styling HTML tables, giving you flexibility over the table, while ensuring they look very slick. The DataTables / Bootstrap integration ensures that you can use all of these features as well as the enhancements that DataTables makes to a plain HTML table.
Installation:
To have DataTables styled by Bootstrap, all you need do, as well as including the DataTables core Javascript file on your page, is include the DataTables / Bootstrap CSS and Javascript integration files. These files simply alter the DataTables defaults, such as class names to use the names used by Bootstrap, and add styling information specific to DataTables.
Both files are both available on the DataTables CDN (below) or you can obtain these files directly from the DataTables integration plug-ins repository on GitHub.

Head over to that link above for more details ...
Bonus tip: there is also an interesting blogpost about this topic ...
PS: I consider Datatables (the module + the library) as one of those hidden Drupal gems, so easy to install/enable, such a great set of features it adds (paging, searching, sorting as you also mentioned). Can't think of a site where we don't use it ... Checkout the questions tagged with datatables for more interesting questions (+ answers) about it.


Change node language from Language neutral to English in bulk using VBO

Oh, yes, I remember this pitfall. Here's what happens: assuming the default language of your site is English, any Language Neutral node is assumed to be English. If you look at the node table in the database, you'll see that their language is 'und'. This is per content type, so let's say we have Language Neutral Basic pages. If you now add a Basic page with language English, its body won't be displayed, though if you check the database, you'll see that it's there (and the node's language is 'en').

The moral: all English-language nodes of the same content type must have language set to either 'und" or 'en', or the ones set to 'en' won't display. On our site, we set the critical content types to Require language (Don't allow Language Neutral). (Under Admin -> Structure -> Content types -> Edit -> Multilingual settings.)


Multisteps Webform loses current page when refreshing browser

For this purpose I use Multi-step forms module. This does all the heavy lifting for you. It allows you to use a session storage so if the page gets refreshed or the browser gets closed, it saves the current step.
Multi-step forms:

Mforms module is a set of tools that help to create advanced multistep forms in Drupal. It can be modified and extended so a developer has full control of the way how individual form steps will be handeled, how and where will data be between form steps stored, which step will follow, how form controls will act and how the output will be displayed.
The main differences from existing multistep solutions for Drupal are robustness, flexibility and extensibility. You can even dynamically change the steps sequence and jump from one step to another regardless of their order.
Read documentation.


Fatal error: Class 'Browser' not found : After Updating drupal 6.20 to 6.26

The error message says eval()'d code on line 4. You have a PHP block, node or something similar that tries to include a file called Browser.php. That is not a file supplied with Drupal core. What you can do... just before line 1731 add something like if(strpos($code, 'Browser.php')) { file_put_contents('/tmp/log', print_r(debug_backtrace(), TRUE)); exit;} and then study the log to see where it's called from to figure it out. If it's called from block, the backtrace will contain the module and delta, if it's a node, the nid will be there and so on.


Actually, the project menu token allowed me to find a good work around. I set it up as pictured below. By using the token [site:url] followed by an existing path, a effectively have a link to an existing node without changing the existing nodes current parent menu.


Drupal Behaviors uncaught reference error

You will have to add the core library core/drupal to your library dependencies. This assures, that the Drupal core JavaScript is loaded before your custom module's JavaScript will be executed.

So your mycustomblock.libraries.yml should look like:

custom:
  version: 1.x
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings


How do I create a template for custom display mode of user registration form?

If you want to add template by Form mode try the following:

/**
 * Implements theme_theme_suggestions_alter().
 */
function YOURTHEME_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  if ($hook == 'form' & !empty($variables['element']['#id'])) {
    /** @var \Drupal\Core\Entity\Entity\EntityFormDisplay $form_display */
    $form_display = $variables['element']['#process'][1][0] ?? NULL;
    if ($form_display) {
      $suggestions[] = 'form__' . str_replace('-', '_', $form_display->getMode());
    }
  }
}


Limited popup like once per month and user

check if

splashify module can help you here

  Display a splash page anywhere on your site by redirecting the user,
  showing a lightbox, or displaying a popup. This module is designed to
  be search engine friendly, mobile device friendly and offers multiple
  configuration options.Instead of using cookies to determine when the
  splash page shows up, we use jStorage.

Popup Message

  Display popup message for users once per browser session.


infinit redirection loop with lightbox2 module

Fragments are not sent to the server as part of a GET request.  That's why you aren't detecting them.  You could try adding a query parameter, so the request would look like this...

http://www...com/node/5/?lightbox=yes#lightbox=<whatever>


Communicating with Drupal from Javascript/Jquery (Drupal 7)

You can send variables to your JS with drupal_add_js() in the $settings array.

An other way (the dirty one) to do it would be to print your data in a hidden div and read it with your JS. (don't hesitate to ask if you need code to do it)

Have fun !


How to restrict content for Anonymous users after they viewed more than two articles?

Not sure if it is the only way to get this to work, and not sure if it is the most elegant way, but it should be doable as detailed below. It does not require any "custom" code, only some (often used) contributed modules.

Rule 1 - Count the visits

The Flag module can by used to flag (eg) articles, which itself can be done automatically (behind the scenes) via the Rules module (= 1st rule). To make the Flag module work for anonymous users also, you'll need to get the Session API involved. For more details on that, refer to:

My answer to "How to display a flag to anonymous users?".
The great article about Enhancing the Anonymous User Experience: Adventures with Flags.

Rule 2 - Trigger the redirect

With that, you have "a" counter (= number of articles flagged by a user) that you can use as a Rules Condition in a 2nd rule, whereas this 2nd rule can be triggered by a Rules Event like "after an article gets flagged". In that Rules Condition you just check if the counter exceeds your limit (= 2 in your case), then you perform the Rules Action (in the 2nd rule) which is to redirect to your login/register page.


How to change views pager with View All links

The only way I can think of you achieving such a thing would be to create another display page in addition to the display page which already has a pager. And using html/CSS add a link to the footer of the views with pager called View all linking to the display page you created that shows all content.


Switch the active theme to a core theme. If the library loads now then make sure that your custom theme has <js-bottom-placeholder token="{{ placeholder_token }}"> and  <js-placeholder token="{{ placeholder_token }}"> in the html.html.twig template.

Another pitfall is an incorrect reference to the library. Although it does not apply to the original question I'll state it anyway because it solved the problem for me. If your my_module.libraries.yml looks like this

my_libraries.my-library:
  js: ...

then you have to use

['#attached']['library'][] = ['my_module/my_libraries.my-library']

instead of

['#attached']['library'][] = ['my_libraries.my-library']


What you may be looking for is "Contextual Filters"

Here's a good tutorial I have that explains how to implement them:

http://www.youtube.com/watch?v=lJFMTDuaxy8

There's also a way to call a View directly from a template, which can be pretty useful in some cases:

views_embed_view("slideshow_gallery", "page", array() );


Can't insert data to database on form submit

your schema

<?php
function form_example_schema() {

    $schema['form_example_table'] = array(
        'description' => 'Table for form_pokus module',
        'fields' => array(
            'id'        => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
            'name'      => array('type' => 'varchar','length' => 30,     'not null' => TRUE, 'default' => ''),
            'gender'    => array('type' => 'varchar','length' => 30,     'not null' => TRUE, 'default' => ''),
            'message'   => array('type' => 'text', 'not null' => TRUE,   'default'  => ''),
            'status'    => array('type' => 'text', 'not null' => FALSE ),
            'created'   => array('type' => 'int',  'not null' => TRUE,   'default'  => 0),
        ),

        'primary key' => array('id'),

    );

    return $schema;
}
?>

needs to look like:

function form_example_schema() {

    $schema['form_pokus_table'] = array(
        'description' => 'Table for form_pokus module',
        'fields' => array(
            'id'        => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
            'name'      => array('type' => 'varchar','length' => 30,     'not null' => TRUE, 'default' => ''),
            'gender'    => array('type' => 'varchar','length' => 30,     'not null' => TRUE, 'default' => ''),
            'message'   => array('type' => 'text', 'not null' => TRUE,   'default'  => ''),
            'status'    => array('type' => 'text', 'not null' => FALSE ),
            'created'   => array('type' => 'int',  'not null' => TRUE,   'default'  => 0),
        ),

        'primary key' => array('id'),

    );

    return $schema;
}

you had the wrong table name as the schema index.


How to populate a node reference field that has multiple values?

I managed to get multiple value node reference field using the Array Tokens module, an extension to the Token module, providing tokens for multiple-value CCK fields and taxonomy terms.

$authors = array([node:field_op_author-default-array-nid]);
$options = array();

foreach ($authors as $author) {
  $options[] = array('nid'=>$author);
}

return($options);


How to build an install profile progmatically

The questions you are asking are pretty hard to crack. We have build Kraftwagen which is a Drush extension and a bunch of Drupal modules that will fit your needs.

Please have a look and let us know if it worked for you.


There are many possible reasons how the code wound up being like that. If you could remove the inline styles for margins, height and width and instead add the class "img-responsive" to the image it would render in a more "standard" and expected way on the page. Alternatively you could add

width: 100%; height: auto;

to the inline style, but that would only be a "emergency" solution and not be considered good practice.

However it would probably be best to cleanup the markup so that the caption lives in a div or span with a class name of caption. Why are you not making use of the default caption option in Drupal? If you look at or install a "clean" version of Drupal 8 and create an article and add an image you can see how the caption works. It generates this markup:

This is my nice caption


How do I hide a local task (tab) if a module is disabled?

I believe my problem was that if the module was disabled then the route would not exist - and this would have my links.task.yml trying to create a local task from a non existent route.

My solution was to generate a dynamic local task instead, so that the local task is only created, if the module is enabled:

mymodule.links.task.yml

mymodule.bravo:
  deriver: 'Drupal\mymodule\Plugin\Derivative\BravoLocalTasks'

src/Plugin/Derivative/BravoLocalTasks.php

namespace Drupal\mymodule\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;

/**
 * Generates local tasks.
 */
class BravoLocalTasks extends DeriverBase {

  /**
   * {@inheritdoc}
   */
  public function getDerivativeDefinitions($base_plugin_definition) {
    $moduleHandler = \Drupal::service('module_handler');
    if ($moduleHandler->moduleExists('statistics')) {
      $this->derivatives['mymodule.bravo'] = $base_plugin_definition;
      $this->derivatives['mymodule.bravo']['route_name'] = 'mymodule.bravo';
      $this->derivatives['mymodule.bravo']['base_route'] = 'mymodule.alpha';
      $this->derivatives['mymodule.bravo']['title'] = 'Bravo';
    }
    return $this->derivatives;
  }
}

I believe I will have to create a distinct class for every route that requires dynamic local tasks.

If you have a better solution, please post.


How to display the same field with various nodes in the same row using Views?

Yes, simply

Add the field relationship your View
Add the required fields to the view
On the relevant field configuration form, select the relationship to use.

For example:

"Title" ( no relationship ) to select from base table and
"Title" ( with relationship ) to select from related data.


How to create a special autoincrement field?

The obvious option would be to have a serial field for each type. Whether or not that is feasible based on your business rules (are there lots of types, are the types likely to change, etc.) is another question.

Another module that may be very useful in these types of problems is the computed field module.

Another option (probably the one I would choose) is to make it completely custom.
Either a custom entity property or a custom field of some sort that does database queries to determine the next value instead of auto_nodetitle + serial module + rules.
Be careful of race conditions when doing something like this though.


Saving values of a multistep form into custom entity fields

After struggling for a couple of days I finally was able to store the values in the entity.

The first mistake was that I forgot to pass my entity ('organisation') as an argument in the primary hook_form:

  // Return the current form
  $function = $form_state['storage']['step'];
  $form = $function($form, $form_state, $organisation);
  return $form;

The second was that I had to build and save my entity each step with the code I attached in this question.

$organisation = entity_ui_form_submit_build_entity('organisation',$organisation, $form, $form_state);
$organisation->save();

Now I have my custom entity with custom fields and a multistep conditional adding form!

This is the code if someone else need the same functionality.
Primary form and submission functions:

function organisation_form($form, &$form_state, $organisation) {
  if ($form_state['rebuild']) {
      $form_state['input'] = array();
  }
  if (empty($form_state['storage'])) {
// No step has been set so start with the first.
   $form_state['storage'] = array(
      'step' => 'organisation_first_form',
   );
  }
// Return the current form
  $function = $form_state['storage']['step'];
  $form = $function($form, $form_state, $organisation);
  return $form;
}

function organisation_form_submit($form, &$form_state) {
 $values = $form_state['values'];
 if (isset($values['back']) && $values['op'] == $values['back']) {
   // Moving back in form.
   $step = $form_state['storage']['step'];
   // Call current step submit handler if it exists to unset step form data.
   if (function_exists($step . '_submit')) {
     $function = $step . '_submit';
     $function($form, $form_state);
   }
// Remove the last saved step so we use it next.
$last_step = array_pop($form_state['storage']['steps']);
$form_state['storage']['step'] = $last_step;
  }
  else {
   // Record step.
   $step = $form_state['storage']['step'];
   $form_state['storage']['steps'][] = $step;
   // Call step submit handler if it exists.
   if (function_exists($step . '_submit')) {
      $function = $step . '_submit';
      $function($form, $form_state);
   }
  }
return;
}

This is one of the steps and its submission function.

function organisation_second_form($form, $form_state, $organisation) {
  $form['#parents'] = array();
  // These variables are needed to build field forms.
  $entity_type = 'organisation'; // Substitute with any entity type.
  $bundle_name = 'organisation'; // Substitute with the entity's bundle.
  $entity = $organisation;
  $langcode = LANGUAGE_NONE; // Substitute as appropriate.

  $field_name = 'hub_position_activities';
  $items = field_get_items($entity_type, $entity, $field_name);
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);
  $field_form = field_default_form($entity_type, $entity, $field, $instance, $langcode, $items, $form, $form_state);
  $form += $field_form;

  $field_name = 'hub_market';
  $items = field_get_items($entity_type, $entity, $field_name);
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);
  $field_form = field_default_form($entity_type, $entity, $field, $instance, $langcode, $items, $form, $form_state);
  $form += $field_form;

  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('Back'),
    '#limit_validation_errors' => array(),
    '#submit' => array('organisation_second_form_submit'),
    '#weight' => 499,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Next'),
    '#weight' => 500,
  );
  return $form;
}

function organisation_second_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;
  if (isset($values['back']) && $values['op'] == $values['back']) {
    $input = $form_state['input'];
    // The user clicked the back button, save values that were input
    if (isset($input['hub_position_activities'])) {
      $form_state['storage']['hub_position_activities'] = $input['hub_position_activities'];
    }
    if (isset($input['hub_market'])) {
      $form_state['storage']['hub_market'] = $input['hub_market'];
    }
    $form_state['storage']['step'] = 'organisation_first_form';
  }
  else {
    $form_state['storage']['hub_position_activities'] = $values['hub_position_activities'];
    $form_state['storage']['hub_market'] = $values['hub_market'];
    $organisation = entity_ui_form_submit_build_entity($form, $form_state);
    $organisation->save();
    $form_state['storage']['step'] = 'organisation_third_form';
  }
}

And the last submission function.

function organisation_last_form_submit($form, &$form_state) {
  $values = $form_state['values'];

  if (isset($values['back']) && $values['op'] == $values['back']) {
    $form_state['storage']['step'] = 'organisation_second_form';
    $form_state['rebuild'] = TRUE;
  }
  else {
    $form_state['storage']['hub_equipment_measurement'] = $values['hub_equipment_measurement'];
    $form_state['storage']['hub_equipment_software'] = $values['hub_equipment_software'];
    $organisation = entity_ui_form_submit_build_entity($form, $form_state);
    $organisation->save();
    drupal_set_message(t('The organisation: @name has been saved.', array('@name' => $organisation->name)));
    $form_state['redirect'] = 'admin/organisations';
  }
}

Perhaps there were easier way to achieve this goal but, so far, is the only one that worked for me. If anyone has better solutions I'm eager to know them.

Thanks to Alex Weber for his great tutorial on how to get the form for existent fields http://www.alexweber.com.br/en/articles/how-manually-add-entity-field-forms-custom-drupal-form and to Bryan Jones for his Multi-step form tutorial http://bryanjones.us/article/custom-multi-step-forms-drupal-7


Loading a View Through Ajax - Slideshow not showing

Are you using a Drupal module like Views Slideshow to create your slideshow?

Usually slideshows will need to dynamically calculate the height/width of the content in the slides in order to render correctly. If the slideshow is hidden when the slideshow's javascript is loaded, then there will effectively be no content for the slideshow's javascript to render, thus the slideshow will never render correctly.

Does the slideshow render with no problems if you remove your CSS and/or JS that hides (and then slides down) the slideshow?

I haven't dealt with this sort of issue directly, but hopefully I can point you in the right direction. I would guess that somewhere you are using JS or CSS to hide the #portslide-wrap div (i.e. display:  none;) until it is ready to slide down? I would suggest trying to hide that div behind some other element using z-index rather than display:none(so that the slideshow can render while being obscured) and then hide it using JS after the slideshow has processed (probably a class like "slideshow-process" is added to a wrapping div, which you can use to hide the slideshow via CSS).


This is my solution for adding title to page templates.
in yourthemename.theme add

function hook_preprocess_page(&$vars) {
    if(isset($vars['node'])) {
        $vars['title'] = $vars['node']->title->value;
    }
    else{
       $vars['title'] =$vars['page']['#title'];
    }
 }

then title exist in page templates.


Changing the tite of your page to match the title of your tabs

You have to call

> 4.6 – 6   drupal_set_title($title = NULL)
> 7 – 8     drupal_set_title($title = NULL, $output = CHECK_PLAIN)

You'll have to change your code around a little

  $items['admin/settings/cvminterviews/setup'] = array(
    'title' => 'Interview Schedule Setup',
    'description' => 'Setup',
    'file' => 'cvminterviews_admin_setup.inc.php',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('cvminterviews_dateroomsetup_form'),
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_LOCAL_TASK,
  );

to

  $items['admin/settings/cvminterviews/setup'] = array(
    'title' => 'Interview Schedule Setup',
    'description' => 'Setup',
    'file' => 'cvminterviews_admin_setup.inc.php',
    'page callback' => '_cvminterviews_admin_page',
    'page arguments' => array(
      'variables' => array(
        'form' => 'cvminterviews_dateroomsetup_form',
        'title' => t('my_title')
      )
    ),
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_LOCAL_TASK,
  );

function _cvminterviews_admin_page($variables = NULL) {
  if(isset($variables['title'])) {
    drupal_set_title($variables['title']);
  }
  if(isset($variables['form'])) {
    return drupal_get_form($variables['form']);
  }
}

Then do the same thing for $items[admin/settings/cvminterviews'] & $items['admin/settings/cvminterviews/setup']

When you are changing your code, there is one more problem that you will need to aware of.

There will be 2 tabs on admin/settings/cvminterviews,  one that will be active 'Overview' and 'Interview Schedule Setup'.  'Overview' will link to admin/settings/cvminteviews NOT admin/settings/cvminterviews/overview.  admin/settings/cvminterviews/overview will never be called (unless you type that it into the address bar) because it is the default tab set by 'type' => MENU_DEFAULT_LOCAL_TASK.


How to define and use an external database connection in a custom module

There's no particular place to put this code (hook or module), you just put it where you need it.
So it should go just before your queries on the other database and just after to set back the default DB.

If all your module will rely on the external DB just put it a the beginning of the first function called for your module and at the end of the last function.

Of course every one of your function should be executed on the external DB and nothing must have to query the default database without switching back.

This following code would fail:

db_set_active('YourDatabaseKey');

$result = db_query('SELECT ...'); //Your own queries on the external DB.

$node = node_load(123); //This would fail on the external DB.

$result = db_query('SELECT ...'); //Your own queries on the external DB.

db_set_active();

You should switch back and forth:

db_set_active('YourDatabaseKey');

$result = db_query('SELECT ...'); //Your own queries on the external DB.

db_set_active();
$node = node_load(123); //Query made on the default Drupal DB.
db_set_active('YourDatabaseKey');

$result = db_query('SELECT ...'); //Your own queries on the external DB.

db_set_active();


This can happen when there are problems with your local .htaccess file -- it might be that Apache locally is not set up to read .htaccess files, or there may be an error in the file, or it may be missing altogether.

If the issue is specifically with the login form, you might be having issues with HTTP/HTTPS switching if your site is configured to attempt to negotiate the scheme, but your local server is not configured to serve HTTPS.


Replace menu's ul li.first a text link with image  link

You can override theme_menu_tree.  All it does is output UL tags, so you could squeeze in an LI at the beginning, like this:

    function mycustomtheme_menu_tree($variables) {
      $path = drupal_get_path('theme', 'mycustomtheme') . '/images/home.png';
      $image = theme('image', array('path' => $path, 'alt' => t('Home'), 'title' => t('Home')));
      $home_link = l($image, '', array('html' => TRUE));
      $home_li = '
' . $home_link . '
';
      return '
' . $home_li . $variables['tree'] . '
';
    }

I've done this exact thing on several sites (but I use nice_menus), here's the code I added to my template.php file in my custom theme:

    function mycustomtheme_nice_menus_tree($variables) {
      $menu_name = $variables['menu_name'];
      $mlid = $variables['mlid'];
      $depth = $variables['depth'];
      $menu = $variables['menu'];
      // Load the full menu array.
      $menu = isset($menu) ? $menu : menu_tree_all_data($menu_name);
      if (isset($menu)) {
        $page_menu = menu_tree_page_data($menu_name);
        $trail = nice_menus_build_page_trail($page_menu);
        unset($page_menu);
      }

      // Allow i18n module to translate strings where available.
      if (module_exists('i18n_menu')) {
        $menu = i18n_menu_localize_tree($menu);
      }

      // Assume depth == 0 by default, overriden if mlid is specified.
      $parent_depth = 0;

      // For custom $menus and menus built all the way from the top-level we
      // don't need to "create" the specific sub-menu and we need to get the title
      // from the $menu_name since there is no "parent item" array.

      // Create the specific menu if we have a mlid.
      if (!empty($mlid)) {
        // Load the parent menu item.
        $item = menu_link_load($mlid);
        // The depth for our parent item, if it exists.
        $parent_depth = ($item['depth']) ? $item['depth'] : 0;

        // Narrow down the full menu to the specific sub-tree we need.
        for ($p = 1; $p < 10; $p++) {
          if ($sub_mlid = $item["p$p"]) {
            $subitem = menu_link_load($sub_mlid);
            // Menu sets these ghetto-ass keys in _menu_tree_check_access().
            $menu = $menu[(50000 + $subitem['weight']) . ' ' . $subitem['title'] . ' ' . $subitem['mlid']]['below'];
          }
        }
      }

      $output['content'] = '';

      if ($menu) {
        // Set the total menu depth counting from this parent if we need it.
        $depth =  ($depth > 0) ? ($parent_depth + $depth) : $depth;
        $output['content'] .= theme('nice_menus_build', array('menu' => $menu, 'depth' => $depth, 'trail' => $trail));
      }

      /* my changes */
      $path = drupal_get_path('theme', 'mycustomtheme') . '/images/home.png';
      $image = theme('image', array('path' => $path, 'alt' => t('Home'), 'title' => t('Home')));
      $home_link = l($image, '', array('html' => TRUE));
      $home_li = '
' . $home_link . '
';

      $output['content'] = $home_li . $output['content'];
      $output['subject'] = '';

      return $output;
    }


How to translate the description metatag for a view

You could add something in the html.tpl.php along these lines:

  <?php
  if((function_exists('views_get_page_view') && views_get_page_view()) && ($language->language == 'fr')){ ?>
      ...Your metatag here...
  <?php
  }elseif((function_exists('views_get_page_view') && views_get_page_view()) && ($language->language == 'de')){ ?>
      ...Your metatag here...
  <?php } ?>

  views_get_page_view() finds out what, if any, page view is currently
  in use. If it returns NULL, then the current page is not a views'
  page.

Source

This line of code may come in handy as well, to figure out which view:

$view = views_get_page_view();

Source

Is this enough to help you on the way?


How to move a drupal 6 installation to a new server?

Do you have mod_rewrite for Apache enabled/installed?  If not, verify this is the case.

Also, ensure that your .htaccess file in your Drupal root is unchanged from the old server.

If you're on a Debian-based distribution, go to /etc/apache2/mods-available to verify that rewrite.load is present.  Then go to /etc/apache2/mods-enabled to verify that rewrite.load is symlinked in that directory.

If you're on a RedHat distro like CentOS, then go to /etc/httpd/modules and look for mod_rewrite.so.  Then, open up /etc/httpd/conf/httpd.conf and verify that this line is in there LoadModule rewrite_module modules/mod_rewrite.so.


Why drush fails with undefined function conf_path() error?

Without knowing what command you're trying to run or your file structure, it's difficult to say.

Most commonly this happens when your drush has trouble bootstraping your Drupal root, either by corrupted Drupal core files or different loading the wrong files.

In example if you run drush inside Panels module directory it fails, because it contains includes/common.inc file and drush is confused that it's Drupal core version of common.inc so it's loading it and expects that conf_path() should be defined. The same with core/includes/common.inc. Check the _drush_bootstrap_drupal_site_validate() function at drush API site.

I believe this has been fixed in the recent drush (see #60 at GitHub and original issue), so please upgrade it to the recent version (see the instructions).

However in some other circumstances the problem is still happening (#937) for some reason.


Add views exposed filter programmatically

OK the code is working fine, the only problem was that the color field was added to product, while views was set based on node, so when I added a relation to product, it started working.


At the time of writing Drupal does not work out-of-the-box with HipHop VM (1). Some people have managed to make it work with previous versions, but there isn't a simple easy option.

On php.webtutor.pl you can find a number of useful resources:

A benchmark of Drupal comparing standalone PHP, PHP with APC, and HipHop ;
The patch that was used to make Drupal run under Hiphop

These are for an older version of Drupal 7 (7.2) and an older version of Hiphop. However the patches are still useful as a place to start. Some of the issues addressed in the patches (eg. the infinite loop caused by drupal autoload) are still current - others may or may not be, I have not investigated further myself though the article by @tvlooy suggests the PDO issues have been fixed.

The article at http://nickveenhof.be/blog/getting-drupal-7-almost-running-hhvm (on which the tests by @tvlooy was based) provides an example configuration - even though the author failed to get Drupal to run under HHVM, it gives a helpful starting point in addition to the webtutor patches.

(1) As tested with Drupal 7.22 and the latest development version of HipHop (HEAD on the master branch) as of 01/08/2013

Edit: A post made on the 12/09/13 (after this answer was written) on the HHVM blog suggests that HHVM now passes 98% of Drupal core unit tests. There has been more HHVM releases since then - a comment on the 2.2.0 release that came out a month later suggests that Drupal 7 can be installed using HHVM, though file uploading, clean URLs and php-gd do not work. I do not want to change my original answer as I have not tested this myself, however the comment (together with the 2.2.0 changelog) suggests that some of the issues, such as the autoload loop, have been fixed.


unlimited number of values gets really big

Put the relationship the other way round, ie let every inhabitant be a separate entity that has an entity reference to a city.

Then you can still display them on a city content view by using an embedded view, such as EVA or Display Suite dynamic field, or using Panels. You can even embed it via a preprocess_node function using view_embed_view, and have pagination on it.

And views will use the inverse relationship just fine.

Look at the wiki entry for Cardinality (data modeling) for more information on this principle.


Although -dev for D7, You could try http://drupal.org/project/dragndrop_uploads

  The Drag'n'Drop Uploads module adds the ability to drag an image from
  your local filesystem, drop it onto a node body textarea and have the
  file automatically uploaded and referenced in your node.


How to prevent CKEditor trim plain text in source view

CKEditor distinguishes Output formatting from Source Code formatting.

You're essentially wanting to do output formatting inside the source code formatting. It seems this is currently not possible.

From the documentation:

  Configuring Source Code Format

  At the moment the only aspect of the source code view that you can configure is the tab-size CSS property of the source editing area. Use the CKEDITOR.config.sourceAreaTabSize option to set the width of the tab character. Enter an integer to denote the number of spaces that the tab will contain.

  http://docs.ckeditor.com/#!/guide/dev_sourcearea

You might play with using the popup source editor instead of the inline editor, I don't know if this would give you any more possibilities to plug into and alter the HTML in source-editing mode or not.


How to edit Commerce to display more than 3 products in a row

Think I found a way to resolve this simply via CSS.

There is this styles in global.css:

  .page-products .view-display-products li:nth-child(3n+4) {
      clear: left;
      /* LTR */
      float: left;
      /** LTR */ }

so we can overwrite it with a sub-theme CSS with "clear:none".

By re-sizing browser window, looks like it still works well when window get smaller.

Earlier on didn't quite look close enough into this, partly due to meddling too  much in Views Format settings. So assuming reverting to default Views setting, the above CSS change should work fine. Will update again if otherwise.

BK :)


How to convert hook_xmlsitemap_links to xmlsitemap 6.x-2.x API?

There doesn't seem to be hook anymore to return links for further processing, but
 adding and deleting links is done with calls to xmlsitemap_link_save and xmlsitemap_link_delete(_multiple)

I implemented a hook_xmlsitemap_index_links, which normally is only called when the command drush xmlsitemap-index is issued:

function my_xmlsitemap_index_links($limit) {
  $sql = "SELECT x.id FROM {xmlsitemap} x WHERE x.type = 'my'";
  $query = db_query($sql);
  $indexed = xmlsitemap_db_fetch_col($query);
  //there isn't a lot of stuff, it fits in memory, but fetching it is costly.
  $indexed = array_flip($indexed);
  $mystuff = __my_get_stuff();
  $i = 0;
  foreach ( $mystuff as $thing ) {
    if ( !isset($indexed[$thing->id]) ) {
      # new thing
      xmlsitemap_link_save(__my_make_xmlsitemap_link($thing), $thing->id);
      $i++;
    }
    unset($indexed[$thing->id]);
    if ( $i == $limit )
      return;
  }
  #Done indexing new stuff;
  if ( $indexed ) {
    $deleted = array_flip($indexed);
    xmlsitemap_link_delete_multiple(array('type'=>'my', 'id'=>$deleted));
  }
}

I'm still puzzling on what to return from my hook_xmlsitemap_link_info. It's not at all clear when those callbacks are called.

The process callback is useless for this usecase; xmlsitemap has no way of knowing any foreign IDs.
The rebuild callback is afaik only called by drush and manual action, not a means of keeping the links up to date, but it remains unclear if such a callback is required or optional (although xmlsitemap_custom seems to manage without one)
The settings callback is still a mistery to me, but it's used for the admin.

This hook_xmlsitemap_link_info with my_xmlsitemap_index_links as rebuild callback, makes my module reindex when I issue a rebuild command from the admin.

function my_xmlsitemap_link_info() {
  return array(
    'my' => array(
      'label' => t('My Stuff'),
      'xmlsitemap' => array(
        'rebuild callback' => 'my_xmlsitemap_index_links',
        ),
      )
    );
}

I ended up implementing a hook_cron that periodically calls my_xmlsitemap_index_links, to keep it in sync.

I might update my hook_load, to issue a xmlsitemap_link_delete on failed loads (404's).


Enable admin theme in my install profile

Yes, you just need to set the relevant variable (admin_theme), e.g.

variable_set('admin_theme', 'seven');


How do I check the value of a Boolean field in a template file?

I don't know how you debug but I think from question contest that trying  node.field_checkbox.0.value might work. Or if you are working with views and use views_get_view_results function, try content._entity.field_checkbox.value or content._entity.field_checkbox.0.value 0 used if field is untranslated

Update for comment:

function TEMPLATE_theme_suggestions_page_alter(&$suggestions, $variables) {

  // Check it's a node page.
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {
    array_splice($suggestions, count($suggestions) - 1, 0, 'page__node__' . $node->getType());
  }
}

with this code in your TEMPLATE.theme file drupal 8 suggest page--node--CONTENT-TYPE-MACHINE-NAME.html.twig (Undersores to dushes). and thats it, You might have {{ kint(node) }} or {{ dump(node) }} in your twig.


Your issue is in this line

img = '/sites/all/themes/ave/img/logo2.png';

It should be something like this:

img = location.protocol + "//" + location.host + '/sites/all/themes/ave/img/logo2.png';

and if that does not work just inspect the src param of the image and adjust accordingly.

And perhaps replace the whole script with this:

(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.MYMODULE = {
        attach: function(context, settings) {
            var img = location.protocol + "//" + location.host + '/sites/all/themes/ave/img/logo2.png';
            $('.logo-img a img').attr("src", img);

        }
    };

})(jQuery, Drupal, this, this.document);


Is there a module that creates an input filter to convert text to the ASCII character-set?

If you have the Transliteration module installed, you can create your own filter.

Go to /admin/config/content/formats and click on Add text format at the top. One of the options is Convert all characters to US-ASCII. Set the roles you want to allow use of the format and save.


Look at PHP's array_diff() function:

http://php.net/manual/en/function.array-diff.php

This will compare an array of the roles you're checking for against the array of the user's roles, and return an array containing the leftovers.

<?php
$roles_to_check_for = array('administrator', 'operator');
$users_roles = array_values($user->roles);

if (array_diff($roles_to_check_for, $users_roles)) {
  // User does not have all of the $roles_to_check_for.
}
else {
  // User has all of the $roles_to_check_for.
}


PDOException on Article page : Base table or view not found

As per @Triskelion comment:

When you created the 'tags' field, two tables (field_data_field_tags and field_revision_field_tags) were created to hold the information. If the first table is present but the second is not, use a statement like CREATE TABLE field_revision_field_tags AS SELECT * FROM field_data_field_tags; to replace the missing table. If both are missing, then you should restore your database from your latest backup.

If the error is showing, the field has already been created and the database is corrupt. If he tries to recreate the field before trying to recover, he might lose all existing information. Better to begin with the restoration attempt, then move to more drastic measures if restoration is not possible.


Form validation: text has to be a number

Drupal already has a helper for this, in the shape of the element_validate_number() validation callback:

function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['number']['#element_validate'][] = 'element_validate_number';
}

You can also use element_validate_integer() or element_validate_integer_positive if either of those make more sense for your use case.