Behavior handling has changed again in Drupal 7, with modules now required to explicitly define their attach handler, and optionally specify a detach handler. add code like this way.

(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
    $('#headerCarousel.carousel[id]').each(function() {
        var html = '

';
        for(var i = 0; i != $(this).find('.item').size(); i ++) {
            var item = $(this).find('.item').get(i);
            html += '
'  + $(item).attr('data-title') + '

';
        }
        $('.btn-navbar').after(html);
        $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').hide();

    }).bind('slid', function(e) {
        var nav = $('.nav-collapse[data-target="' + $(this).attr('id') + '"] ul');
        var index = $(this).find('.item.active').index();
        var item = nav.find('li').get(index);
        nav.find('li.active').removeClass('active');
        $(item).addClass('active');

        if(index == 0) {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
        if(index == nav.find('li').size() - 1) {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
    });

   $('.bootstrap .nav a').bind('click', function(e) {
       var index = $(this).parent().index();
       var carousel = $('#' + $(this).closest('.nav-collapse').attr('data-target'));
       carousel.carousel(index);
       e.preventDefault();
   });

    }
  };

})(jQuery);


Custom PHP Unit test trait for a custom module cannot be found

The namespace should Drupal\Tests\my_module\Traits - notice this is Tests with an s at the end, not Test


That's because you are doing it the hard way. Why hardcoding everything when views does it out of the box? Views fields are extremely flexible and customizable. You may need to strip the views fields first (style fields and deselect whatever option you have - do that also with your format / html, unformatted etc). Usually, what I do is exclude from display and use views tokens in the last field of type Global text area. This way, the view only displays actually field values, with no html whatsoever.

To escape hard coding even for your content type display, try using display suite. It works smoothly with EVA as well.

I hope I got it right.

And... what is simple when you're trying to achieve complex structures? Is there any other platform delivering something like views OOTB?

There is some research to be done regardless choice of environment. And usually, the shortest, simplest way, is the way you know better.


Form API placeholder attribute rendered as "- Select -"

According to the documentation: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Select.php/class/Select

#empty_option: (optional) The label to show for the first default option. By default, the label is automatically set to "- Select -" for
a required field and "- None -" for an optional field.


Geo field proximity distance for exact location

Zip codes don't have exact location. A zip code is an area in which the coordinates are a point within it. In most cases it is probably the centroid.


D7 Views: Hide field if empty after being rewritten

Go to your view and Click on Keywords to configure the field.
Go to No results behavior and check Hide if empty

That's it. I've tested it and it's working fine. Let me know if you stuck anywhere.


Probably you need to show a default PDF file attachment with custom type nodes. And need to upload some specific to replace the default one via CCK file field.

CCK file field cannot be associated with some default file easily.

The best approach can be...

Place the default document in file system
Edit content-type.tpl.php and check CCK field (e.g. $node->field_name) for file upload
Print the link of uploaded file if exists Else print the link to default file


Limit certain users from filling webform based on their location

You can use a module like Smart IP http://drupal.org/project/smart_ip, GeoIP http://drupal.org/project/geoip or just the Maxmind Geolite http://www.maxmind.com/app/geolitecountry table to look use the IP address of the user to determine the country.

Then use hook_nodeapi() or hook_node_view(), depending on if you are using Drupal 6 or 7, to redirect the person based on the country.

The pseudo code would look something like this (Drupal 6, using Geoip):

function MYMODULE_custom_nodeapi(&$node, $op) {
  switch ($op) {
    case 'view':
      if ($node->nid == 'NODEID OF WEBFORM') {
        $country = geoip_country_code();
        if (isset($country) && $country != 'us') {
          drupal_goto('node/' . NODEID OF REDIRECT PAGE');
        }
      }
     break;
  }
}

edit: When I saw 'webform' I assumed you meant using the webform module, hence the nodeapi, but if you are using the basic site contact form you can use hook_menu and create a new callback for the path of the form you are using and create the same kind of check as above.


Using hook_form_alter to enter placeholder in mailchimp signup fom

You have to use this:

$form['mergevars']['EMAIL']['#attributes'] = array(
 'placeholder'=> t('Your placeholder'),
);


It's good practice to put any code that could potentially throw an exception in a try...catch (not just in Drupal-related code, and not just in PHP).

So yes, it's good practice to put your database queries in a try...catch.


How to access the node title within a field template?

He wants to get the node title in the file link template (I assume that is file-link.html.twig).
You can implement the hook template_preprocess_file_link() in your mytheme.theme file, get the current node and pass its title to twig, something like:

function mytheme_preprocess_file_link(&$variables) {
   $node = \Drupal::request()->attributes->get('node');
   $variables['node_title'] = $node->getTitle();
}

Then, in file-link.html.twig:

{{ node_title }}


To get the taxonomy term name from ID.

function menu_custom_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  dpm($items);
  $element = array();
  foreach ($items as $delta => $item) {
    $taxonomy = taxonomy_term_load($item['target_id']);
    $element[$delta] = $taxonomy->name;
  }
  return array(
    0 => array(
      '#markup' => theme('item_list', array('items' => $item)),
    ),
  );
  return theme('item_list', array());
}

$taxonomy->name  will give you name of taxonomy term.

I hope this will help.
Thanks


TinyMCE Filtered Html is stripping in line styles

if you use filtered html it is by default remove any inline styles or class attribute also javascript tags
you have to make it full html that allowed style
If you want to use filterd html you can use wysiwyg_filter module

It give you control which attibute you can use so you can add inline style


Step back button for Commerece offsite payment method

It's likely you can't, because the form's action will be on a PayPal domain. So it'll always be submitted to them, and your site will never know about it.

The simplest solution would be to use a styled link instead of an input.


How can I get the first character of the node title?

You could try this code:

/**
 * Implements hook_preprocess_HOOK().
 * @param $variables array
 */
function TEMPLATE_preprocess_node(&$variables)
{
  /** @var \Drupal\node\Entity\Node $node */
  $node = $variables['node'];
  $title = $node->getTitle();
  if(_isFirstCharIsVowel($title)){
    $variables['title_addition'] = "D'";
  }else {
    $variables['title_addition'] = "De ";
  }
}

/**
 * Check if the first character is a vowel
 * @param $string string
 * @return bool
 */
function _isFirstCharIsVowel($string){
  $vowels =
    'aàáâãāăȧäảåǎȁąạḁẚầấẫẩằắẵẳǡǟǻậặæǽǣ' .
    'AÀÁÂÃĀĂȦÄẢÅǍȀȂĄẠḀẦẤẪẨẰẮẴẲǠǞǺẬẶÆǼǢ' .
    'EÈÉÊẼĒĔĖËẺĚȄȆẸȨĘḘḚỀẾỄỂḔḖỆḜ' .
    'eèéêẽēĕėëẻěȅȇẹȩęḙḛềếễểḕḗệḝ' .
    'IÌÍÎĨĪĬİÏỈǏỊĮȈȊḬḮ' .
    'iìíîĩīĭıïỉǐịįȉȋḭḯ' .
    'OÒÓÔÕŌŎȮÖỎŐǑȌȎƠǪỌØỒỐỖỔȰȪȬṌṐṒỜỚỠỞỢǬỘǾŒ' .
    'oòóôõōŏȯöỏőǒȍȏơǫọøồốỗổȱȫȭṍṏṑṓờớỡởợǭộǿœ' .
    'UÙÚÛŨŪŬÜỦŮŰǓȔȖƯỤṲŲṶṴṸṺǛǗǕǙỪỨỮỬỰ' .
    'uùúûũūŭüủůűǔȕȗưụṳųṷṵṹṻǖǜǘǖǚừứữửự'
  ;
  // set necessary encodings
  mb_internal_encoding('UTF-8');
  mb_regex_encoding('UTF-8');
  $first = mb_substr($string, 0, 1);
  $vow = mb_ereg_replace('[^'.$vowels.']','',  $first);
  return !empty($vow);
}

This can be used in your .theme or .module file.
This of course will act on all nodes, so you need to add your type checking.
The _isFirstCharIsVowel function can be in a service, I placed it here for simplicity

UPDATE
Credits for vowwl detectioon goes to this https://stackoverflow.com/questions/14268970/how-to-detect-and-echo-the-last-vowel-in-a-word


Step 1. Get the value of only facebook

drush ev '$v=variable_get("social_sharing"); print $v["facebook"]; print PHP_EOL';

Step 2. Remove google_plus from the list

drush ev '$v=variable_get("social_sharing"); unset($v["google_plus"]); variable_set("social_sharing", $v);'


Can I override the title attributes on an H2 tag within a specific drupal region or block?

You can use CSS to style the H2 tag inside a specific block.

Your block should have a unique ID, based on the name of the block.

Your CSS would look something like this:

<style>
#block-your-blockname h2 {
 color: white !important;
}
</style>

Note: you may not need "!important", and that CSS can go in your main CSS file if you want.


How to disable CACHE in VIEW PAGE display

You have to add a cache tag to the View, the name is arbitrary, for example custom-data-list.

You can do this in a view hook:

function mymodule_views_pre_view($view, $display_id, array &$args) {
  if ($view->id() == 'my_custom_data_view') {
    $view->element['#cache']['tags'][] = 'custom-data-list`;
  }
}

or use the module Views Custom Cache Tags.

By this all cache entries that contain the View, for example blocks or pages and the view itself are tagged with this tag.

Now the only thing you have to do, whenever you change the data in the database (this is for all CRUD operations, that write to the database), invoke:

\Drupal\Core\Cache\Cache::invalidateTags(['custom-data-list']);


Multiple form buttons with AJAX, how to update form state storage data?

Please try this, as @4k4 suggested you have to first build a normal form and ajaxify by using #ajax, and from the method defined inside #ajax you can return a $form and any fields inside the wrapper.

// Relevant bit of the form...
$form['#prefix'] = '
';
$form['#suffix'] = '
';

$form['actions']['#type'] = 'actions';

$form['actions']['update'] = [
  '#type' => 'button',
  '#value' => $this->t('Start Form'),
  '#submit' => ['::setAjaxSubmit'],
  '#ajax' => [
    'wrapper' => 'my-form-wrapper',
    'callback' => [$this, 'update'],
    'method' => 'replace',
  ]
];

$form['actions']['reset'] = [
  '#type' => 'button',
  '#value' => $this->t('Reset Form'),
  '#ajax' => [
    'wrapper' => 'my-form-wrapper',
    'callback' => [$this, 'reset'],
    'method' => 'replace',
  ],
  '#disabled' => TRUE,
];

// The AJAX callback
public function update($form, FormStateInterface $form_state) {
//return $form or part inside the ajax wrapper
return $form;
}

// The submit callback
public function setAjaxSubmit($form, FormStateInterface $form_state) {
  $form_state->set('flag_1', TRUE);
  $form_state->set('flag_2', "Started!");
  $form_state->setRebuild();
}


A module to add a field for display as a column in the administration area

You can't easily extend that list directly.

The easiest way is to replace the default user list using Views and probably VBO.

See also Creating a userlist in Views (including custom user fields).


How to Create content type per organic group

You could simply add taxonomy terms to differentiate different content types.


Well, by now I just found that my question is technically wrong. Drupal is not supposed to do any redirect (HTTP 301/302) on access denied errors (HTTP 403). This is not how HTTP works (as mentioned by @Hudri in the comments).

On an access denied error, Drupal replaces the actual page content with the one from the "Default 403 (access denied) page" site setting. The URL being accessed is valid. It's just that we don't have the permission to see its contents.

I just figured what I was actually wanting to do, was telling Drupal not to use that page's regular template file (page--xyz.html.twig) on the case of an HTTP 403 error, but instead, to use a different one.

Found useful instructions on how to theme HTTP error pages here: https://www.axelerant.com/resources/team-blog/customizing-http-error-pages-in-drupal-8


Main menu not showing on cck type content items

Issue was that the url patterns changed and I still had some old items - so for these the menu didn't display. Don't know why, but updating all content items of that type with the new url pattern solved the issue.


How to wrap / manipulate element outputs on a form's checkboxes html?

You could use your get_office_options function and add some html

For example:

$alphas = range('A', 'Z');
    foreach($w_question->get('field_option_radio') as $key => $option){
        $options[$option_id] = '<i></i>'.$option_text;
    }

    return $options;


Drupal Commerce Relationship Description

OK, I think I understand this now, and the Help text is actually correct as it stands.

Each order, it turns out, has a commerce_line_items [note the plural] field attached to it, and it is this field, of unlimited cardinality, that stores all of the commerce_order/commerce_line_item pairs that are associated with this order.  What this relationship does, then, is make the commerce_line_item reference field that is stored in the commerce_line_items field available to the view designer. Once this commerce_line_item reference field is available, all of the fields in the commerce_line_item itself become available.

The thing that was confusing is that the commerce_line_items field does not show up in a Site Builder's "Manage Fields" configuration screens, and I had not been able to find it in the code.  Many thanks to argiepiano, who showed me where to find the definition of the commerce_line_items field [in the commerce_order module], and the place where data is saved into that field [in the commerce_cart module].

So that is the way that this all works ...

... I think.


Only show field type content added by user

I suggest you use views entity reference this link is good tutorial about it .

So first create a views that show the current user company items ( the companies that the author (creator) of them is current user)  then add "Entity reference" display to it , then in your field settings in "Entity Selection" instead simple mode use "Views :Filter by entity reference" Then select your created views entity reference then enjoy it ;)


How to sort language select list on current language context

i think it can be done in a hook_form_alter()

if the options are in $form['languages'], you can do something like :

$language_options = $form['languages'];

then manipulate the array $language_options, until it has the order you need
then override it in form :

$form['languages'] = $language_options;


Theming user_profile_form (the user edit form)

Aside from using the Display Suite module, most methods for theming forms require a bit of code to be written. In the following method I define variables from the form that can be outputted in a template file to fit whatever HTML structure you'd like. I put all of my code in template.php, but you can just as easily make a custom module to do this.

Add a hook_theme() implementation

function YOURTHEME_theme($existing, $type, $theme, $path){
  return array(
    'user_profile_form' => array(
      'render element' => 'form',
      'template' => 'user-profile-form',
      'path' => drupal_get_path('theme', 'YOURTHEME') . '/templates',
      //add '/templates' only if you store template files in an additional folder
    ),

  );
}

This tells the Drupal theming system that there's a template file waiting for it in YOURTHEME/templates.
Next we'll define some variables to pass into that template in a hook_preprocess_HOOK function. We can find the structured array of the form in $variables['form'] and assign the form elements to the variables we'd like to throw around our tpl.php file.

function YOURTHEME_preprocess_user_profile_form(&$variables) {
  $form_inputs = array(
    'account' => $variables['form']['account'],
    'picture' => $variables['form']['picture'],
    'actions' => $variables['form']['actions'],
  );
  $variables['rendered'] = _YOURTHEME_form_variables_render_all($form_inputs);
}

function _YOURTHEME_form_variables_render_all($elements) {
    //Create array to return, with element name as key and element as value
    $elements_array = array();
    //For each element, render it and add it to the array
    foreach ($elements as $key => $element) {
        $elements_array[$key] = render($element);
    }
    //Return array
    return $elements_array;
}

This example will put the general account info fields, the user picture upload field (if pictures are enabled), and the submit actions into a variable called "rendered."
Now that we have defined these variables, we can output them in a template file. Create a template file named user-profile-form.tpl.php in 'YOURTHEME/templates'. This is a demo example:

<div id="new-form">
  <?php echo $rendered['picture']; ?>
  <?php echo $rendered['account']; ?>
  <?php echo $rendered['actions']; ?>
  <input type="hidden" name="form_id" value="<?php print $form['#form_id']; ?>" />
  <input type="hidden" name="form_build_id" value="<?php print $form['#build_id']; ?>" />
  <input type="hidden" name="form_token" value="<?php print $form['form_token']['#default_value']; ?>" />
</div>

Notice the hidden form fields at the end; these include vital Drupal tokens that help secure forms from attack. Your form won't work without them.

When you visit your user edit page, you should now see only some general account info fields and the picture fields. Create different variables in the preprocess function to separate out form elements and place them wherever you wish in the user-profile-form.tpl.php file, adding whatever markup you like.


How to pull commerce_customer_address into the invoices view?

If I read your situation properly, it sounds like you want to establish a relationship from an order to the user account that created it and include a field from the user account in the Views results. If so, the solution is the core Drupal Commerce relationship Commerce Order: Owner. With this relationship, you should be able to put any property or field of the user account responsible for the order into your Views results.

This relationship is a part of the admin Orders View by default, so perhaps there's something else going on in your case. If so, it would be helpful to know more about your customizations.


jQuery once callback function is not called

jQuery once doesn't take a callback as a second parameter. You need to loop over the returned list of elements and apply a callback using one of the standard methods like each:

$('.my_selector', document).once('special-mark').each(function() {
  console.log('this will be called');
});


Running an immutable setup in production

The file containing the credentials for accessing the database, and other site configurations (e.g. the proxy settings, the trusted domains), is inside the server document root (for example, sites/default/settings.php). The answer to Is there any reason for which the content of the server document root would need to be changed when deploying to production? is then yes.

Add to this the fact that the directory for the public files (e.g. the uploaded images attached to nodes) is by default sites/default/files, you have a reason more to preserve one or more directories under the server document root directory in the production environment.


Create a node's author by passing an argument...?

Use views rewrite on username field to create a "create node" link and prepopulate module using tokens from the views. In this case the username token for the author field.


How to programmatically add options to list_text field

Your available widgets for a list field are these: options_select, options_buttons and options_onoff, not list_text, that is the field type.

The widget values can be found on list_field_widget_info_alter(), where the list types are coupled with the widgets.

So I suppose you should update your field instance to use:

'widget' => array(
  'type' => 'options_select', // Drop down button or multi-select
  // OR
  // 'type' => 'options_buttons', // Radio buttons or checkboxes.
);

The way the widget is rendered depends on the cardinality defined on your field. If cardinality is set to 1, the first type will be used (drop down or radio buttons), if cardinality > 1, you'll get a multi-select field or checkboxes.

Assuming this field can only hold one value, you should also add

'cardinality' => 1,

To your field definition.

Leaving you with:

// Create Field
$field = array(
  'suffix' => array(
    'field_name' => 'suffix',
    'type' => 'list_text',
    'cardinality' => 1,
  ),
);
field_create_field($field);

//Create instance
$instance = array(
  'suffix' => array(
    'field_name' => 'suffix',
    'entity_type' => 'user',
    'label' => 'Suffix',
    'bundle' => 'user',
    'options' => array(
     '0' => 'Mr.',
     '1' => 'Mrs.',
    ),
    'widget' => array(
      'type' => 'options_select',
    ),
  ),
);
field_create_instance($instance);


Submitting disabled fields on content entry forms?

As long as security is not a concern, the following can be done:

Use hook_form_alter to create an additional hidden field in the form.
The name attribute of this hidden field should be equivalent to the name of the disabled field.  The value attribute of the hidden field should be equivalent to the currently selected value.
The hidden field needs to be placed at the very END of the HTML form, or at the very lease, immediately after the disabled field.  The reason for this is that, according to the HTTP specification, if you submit multiple fields with the same name, the last field in the flow of the HTML has it's value submitted above all other submissions.  Of course, disabled fields have their values dropped altogether, so the hidden field could technically appear anywhere in the form, but this would be "best practice".

Here's some code from my hook_form_alter:

function ccom_validations_form_challenges_node_form_alter(&$form, &$form_state, $form_id) {
  $form['my_field'] = array (
    '#type' => 'hidden',
    '#value' => 'schweet'
  );
  $defaultValue = $form['field_reporting_period']['und']['#default_value'][0];
  $form['my_field']['#attributes']['name'] = 'field_reporting_period[und]';
  $form['my_field']['#attributes']['value'] = $defaultValue;
  $form['my_field']['#weight'] = '4';
  $form['field_reporting_period']['#disabled'] = 'true';
  dpm($form);
}

So in the above code you can see how I've assigned the name and value to the field, adjusted the weight so it appears last in the list (using DPM I found that the the highest weight value was 3 in the form, so I used 4 so it was weighted the heaviest), and finally indicated that the original field I wanted disabled is in fact disabled.  Note that you disable form fields in Drupal using the meta attribute #disabled, rather than specifying the disabled attribute directly in the #attributes array.  Weird.

Now this obviously isn't secure, because anybody with any browser HTML manipulation tool like the Chrome Inspector can enable the field and move it to last in the list and then it's value would be used rather than the hidden fields.  I'll revisit this later if security really becomes a concern in this area.


Webform - how do I change dateformat in mail

Try go to admin/config/regional/date-time and set your site's Medium date type format.

Also, if the Medium format doesn't include at least a month, day, and year field, Webform will default to the American format of MM/DD/YYYY.

Webform uses the "medium" in e-mails and viewing submissions, though everywhere else (like a displaying the date component) it uses short for the order


Well I ended up using Hook_form_alter () to add every form that was being called (and was not on my form list yet) to a form list.

Then I wrote an admin interface that enables the administrator to select what forms are still active/should be listed. Next to this I implemented a REST service for the Services module to GET the list of forms.

The fact that the hook_form_alter () has to preform a DB request to see if the form is on the list everytime a form is viewed is some what performance heavy, but since there is no help, this is the best I can think of. If anyone has interest in the code, drop me a line, ofcourse better ideas are welcome;-)


Ubercart Module for handling subscriptions?

Look at UC Recurring module. It should do what you need. The instruction on how to set it up is here.


Use swatches and not the color picker widget

Interesting question - You should try the color field module -

  Color Field is simple field that use a hexadecimal notation (HEX) for
  the combination of Red, Green, and Blue color values (RGB).

This uses the jquery simple color widget

and you can add your colors directly in as hexadecimal codes when you setup the field:


you can use hierarchical_select module for this .


How to setup birthdate field with optional values

I would define 3 optional selects:
 - Year (now() to now() - 100)
 - Month (1-12)
 - Day (1-31)

Then in a hook_node_validate() I would check if only the year is provided or a full date. Also don't forget to verify if the date is valid (like Feb, 31...) using checkdate( int $month , int $day , int $year ).

Then create a field template to either display the age or a birthdate.


Insert values into custom field's extra columns in database

Can you provide more details how did you implement schema, widget, formatter etc.
I guess this link can be helpful for you http://www.slideshare.net/zugec/fields-in-core-how-to-create-a-custom-field


The solution was to index the field as "string", not "fulltext".


What you're needing really is a general overview of Drupal 8 theming using Twig. The parts you're asking about theming here are just Drupal fields like any other, and you can format / render them into the page's HTML however you'd like from the appropriate template file. What that file is called and how you'll reference the fields you've added is dependent on your theme and the names you've set for those fields.

The "Add to Cart form" display formatter doesn't control the inclusion of these fields. It's solely used to render the actual Add to Cart form. The rest of the variation fields are injected into the product display from whatever the currently selected variation on the Add to Cart form is.


How to open product detail when user click on product image?

In view add "nid" fields before image field and make exclude from display.

Click on image field.
Go to "Rewrite Results" section.Check "output this field as link" .In the "link path" put the 'nid'. It will take you the details page of product.
...

You can also create tpl file for product content type details page.
Enjoy


How to make drush to work correctly in Windows?

I'm going to assume that you're trying to ask how to get drush working in windows.

If you consult the documentation there is a windows installer:

  The Drush Windows Installer provides a convenient way to install Drush
  and the components it needs in order to run on Microsoft Windows. You
  may download it from the attachments list at the bottom of this page.
  Please see the installation guide below for instructions on how to run
  the installer.

Furthermore, if you're trying to get drush working before 5.7 there's a manual installation guide if you need to:

  The Drush Make command does not work in Windows 7 / Vista, when using
  Drush release 5.5, 5.6, or 5.7. However, the current development
  version of Drush fixes this issue! The only problem is there is no
  windows installer program for this version.

  No worries. This article provides instructions for manually installing
  the latest development version of Drush in Windows.

Update:

  For example drush sql-dump returns this error :

  'mysqldump' is not recognized as an internal command

This is a seperate and non-drupal issue. This is caused because drush doesn't know the path to mysql.exe. You need to update your paths in order for msqldump to work. Search super user or stackoverflow regarding mysql, windows and or path together in order to get an answer. I used to know this but it's been too many moons.


Drupal 8, override template menu in custom module doesn't work, theme template is called instead

Your module function custommodule_menu_theme() is incorrectly named so hook_theme() isn't evoked and returning incomplete output; it needs, at least, the base hook & render element elements entered so that it knows what hook to target and the render array to supply to the template.

/**
 * Implements hook_theme().
 */
function custommodule_theme($existing, $type, $theme, $path) {
  $theme = array();
  $theme['menu__main'] = array(
    'base hook' => 'menu',
    'render element' => 'menu',
  );
  return $theme;
}


How do I get the host paragraph when a paragraph is referenced in another paragraph?

If you look at the Paragraph class in the module, you will find a public method called getParentEntity that return the parent entity of a Paragraph instance.

So, if you do:

$parent = $paragraph->getParentEntity();

if (isset($parent)) {
  // Your stuff ...
}

You would have the parent entity in the $parent variable. You can chain the method if there is multiple nested paragraphs. I also suggest using the isset method on the $parent variable because I've encounter some weird issues where random paragraphs returns null.


How to add element not appearing on the page via node_view_alter?

hook_node_view_alter() documentation reads:

  This hook is called after the content has been assembled in a
  structured array and may be used for doing processing which requires
  that the complete node content structure has been built.

This means it is for logic that fires after the render array has been constructed, eg changing weights or items in the array you cannot control (items from other modules).

What you are looking for is hook_node_view(). That should allow you to add new sections into a render array.

The example from the linked resource:

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


Fatal error: Call to undefined function lock_initialize()

The function is called using code similar to the following, from Drupal.

  // Initialize the lock system.
  require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
  lock_initialize();

_drupal_bootstrap_variables() is the only Drupal function that calls lock_initialize().

That code could fail if the file whose name is contained in lock_inc doesn't exist, but in that case I would expect another warning/error message, or it doesn't contain a function called lock_initialize().

I would check if there is code that sets $conf['lock_inc'], and which value is used. I would also check if there is code calling variable_set('lock_inc', ...).


Click on the field in the filter section, and you'll see a "Label" option.


Hide content types in administration for certain user

You should use Content Access module

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.


Is there a way to link a menu item to the edit page of the last article?

Yep!

Create a view that loads the single last published article,  style the view to look like your regular node page and then add a link to the view in your menu.

you could get fancier, but this is the least amount of PHP.


as i see in the console, you are using jquery.min.js?v=1.9.1

and lightbox.js is giving this error:

  TypeError: $.browser is undefined

because this function has been remove since 1.9

I'll suggest you to use default jquery version 1.4.2 where $.browser is deperecated but should work or use another ligtbox module like colorbox


How to extend the user registration in Drupal 7

you can add any action you want after user registered by implementing hook_user_insert.


drush xmlsitemap-regenerate domain is incorrect

Did you set your default base URL under the 'Advanced' fieldset. in admin/config/search/xmlsitemap (D7 version) ?


'drush' is appended to each path breaking its commands

I haven't used Drush under Windows, but something tells me that the problem could be solved by by editing the path to the Drush executable, perhaps in a Windows environment variable.


No, the part in the documentation is not referring to file uploads, but indeed to mail sending. The expected array structure can look like this:

'attachments' => array(
  array(
    'filename' => 'text.csv',
    'filepath' => $filepath,
    'filemime' => 'application/csv',
  ),
),

or

'attachments' => array(
  array(
    'filename' => 'text.csv',
    'filecontent' => 'test content',
    'filemime' => 'application/csv',
  ),
),

Also have a look at this for another example: https://drupal.org/comment/5617230#comment-5617230

Edit: The attributes that you can use

filename: This is the name of the file as it will appear for the mails recipient. So you can freely choose this name.
filepath: If you want to attach a file that exists on your server, then this is the attribute that you want to use. Specifiy the full path to the file (e.g. image).
filecontent: If the attachement doesn't exist on your server but you want to send some content as an attachment, then you can use this attribute to pass on the content.
filemime: Here you can specifiy the mimetype of your attachment. This information gives the users mail application some basic information what to do with the attachment. An attachment of type application/pdf will probably open in the local pdf application, if the mimetype is image/jpeg it will probably open in an image viewer application.

filepath and filecontent are somewhat mutual exclusive. I'm not sure what will be the result, when you specify both.


How to load all remaining content of a view after clicking a "load more" link?

You need Views show more module with ajax under views advanced setting. This module provides Initial item selection option, and rest of the item you can put in the section of on-click.

Steps-

Download and enable the module.
Select show more pager in the Pager section as shown in the image. Then go for setting for that. Now in my case I took 15 items, and I want to initially show 5 items and on clicking rest of the item. So I did put 5 under the Initial items and 10 items under Items to display as shown in second image. And under Animation section select Scroll to new content. Save this, so pager setting ends here.
Under advanced setting of views enable, Use Ajax: Yes

Views Block UI

Pager UI

Out put image:

Initial stage

After clicking show more

It does not require the page refresh to load content.


Welcome email after user reset password in first time?

You can do by using Login one time module

  Rules:

  [user:login-one-time] token on user events.
  [comment:login-one-time] token for node author on comment event.

  User profile - "Send login one time link" button.

  VBO - Create a view and send login links to the view. Checkout View
  Reference for ideas on how to embed views.

  Block - Select a user and send the link. You can use this block in
  nodes as a CCK field using Block Reference.

  PHP - Print a button in a template or directly send the emails using
  the functions described in the README.


viewMultiple() also optimizes the rendering process by returning a common #pre_render callback in the build array, see the discussions and linked topics here Twig: "for" does not display variable content without first displaying all variable content, so you can't put the output directly in #items.

So building each node on its own is the way to go and you probably won't find any differences in performance, because both methods result in the same caching mechanism.


How to show more than two fields in a Openlayers popup on a views_geojson layer?

So, if anyone else runs into this a simple rewriting of the fields in views will get you to where you want. You can add your html there to format the fields.


Embed unique custom form in all rows of a view

That's a lot questions in one post. Two things may help you:

First, if you have more than one instance of a form on one page, you need different formIds. So implement the getFormId with a variable, like so:

public function getFormId() {
    return "mysuper_form-".$this->whatEverCounter;
}

Then, you will need to create your form yourself with the constructor (cause you need your state to be set from outside) and pass that instance to the formBuilder, for example like so

$idForm = new myForm($whatEverCounter);
$form = \Drupal::formBuilder()->getForm($idForm);

Second, for the "each row" topic:
If you really have one form per row, you will have one submit per row also - no problem. Or, you have one form with one element per row. Then just enumerate your elements like so:

public function buildForm(array $form, FormStateInterface $form_state) {
    foreach ($ems as $e) {
       $form['toggle'.$e] = []
    ]

If you need an ajax submit callback, use the '#ajax' attribute, like so:

'#ajax' => array(
        // Function to call when event on form element triggered.
        'callback' => [$this, 'toggleButtonPress'],
        // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
        'effect' => 'fade',
        // Javascript event to trigger Ajax.
        'event' => 'click',
        'progress' => array(
        // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
        'type' => 'throbber',
        // Message to show along progress graphic. Default: 'Please wait...'.
        'message' => NULL,
        ),


You shouldn't return fetched array as result, in Drupal ajax the return value from the ajax function actually overwrites the wrapper, so you've got to set $form['vehicle_model']['#options'] with fetched value and the return this piece of form ($form['vehicle_model']) as function return value. so the code will be something like this :

function _ajaxfunction(array $form, FormStateInterface $form_state) {
  $vehicle_make = $form_state->getValue('vehicle_make');
  $subquery = \Drupal::database()->select('vehicle_model', 'md');
  $subquery->join('vehicle_make', 'mak', 'md.make_id = mak.make_id');
  $subquery->fields('md', ['model_id','model_name']);
  $subquery->condition('md.make_id', $vehicle_make);
  $results = $subquery->execute(); $options_models = array();
  foreach ($results as $result) {
    $options_models[$result->model_id] = $result->model_name;
  }
  $form['vehicle_model']['#options'] = $options_models;
  return $form['vehicle_model'];
}


I assume you use something like Entity reference to add children to parents and to teachers.

I don't think that default Drupal supports this kind of user permissions. As I couldn't find any modules for this functionality, you probably need to do some coding.

The easiest approach would be altering the user/%uid/edit menu item with a custom access callback in a custom module. This ensures users can only access the user edit pages matching your criteria:

function MYMODULE_menu_alter(&$items) {
 if (isset($items['user/%user/edit'])) {
   $items['user/%user/edit']['access callback'] = '_mymodule_user_edit_access';
  }
}

function _mymodule_user_edit_access($account) {
  global $user;

  // May edit own profile
  if ($account->uid == $user->uid) {
    return TRUE;
  }

  // Check if $user has permissions to edit $account
}

The access callback should check if the $user has role Teacher or Parent and if it is referencing to the $account->uid.

Edit:

I just realize you also need to manage profile view rights, this could be done with the same hook, on path user/%user.


Looks like you're struggling with the issue about Date comparison not working.

You may want to try the steps explained in Comment # 20, to configure the timestamps.

If that doesn't work, then try what's suggested in Comment # 19, ie:

  Use the Views Date Format SQL module to format the date on the database server, prior to rendering by Views. This will allow for comparisons in Views Conditional.


Can Date API/Calendar and CCK send an argument to Views with data from a field?

It sounds like you need to do a relationship to the parent node, and then use a Filter by node published date using that relationship.


Disable user language setting in user-edit page

I created both the mentioned projects and I have maintained them for a while. (I stopped maintaining Drupal 6 and 7 modules.)

The code used in the Disable user language module is not correct: unset() should never be used for form elements, as this would cause problems to modules that try to access the form element.

The correct code is the following one. It would preferable if the code would be executed after other modules execute their own code.

/**
 * Implements hook_form_alter().
 */
function mytheme_form_alter(&$form, $form_state, $form_id) {
  // The language selector is only displayed if there is more than one language.
  if (drupal_multilingual()) {
    if ($form_id == 'user_register_form' || ($form_id == 'user_profile_form' && $form['#user_category'] == 'account')) {
      if (count(element_children($form['locale'])) > 1) {
        $form['locale']['language']['#access'] = FALSE;
      }
      else {
        $form['locale']['#access'] = FALSE;
      }
    }
  }
}

In my module I also used hook_init() to change $user->language to a default value; differently $user->language would have the last value saved.

/**
 * Implements hook_init().
 */
function dul_init() {
  if (!user_access('change own user language')) {
    global $user;

    $user->language = language_default('language');
  }
}

Clearly, the Disable user language module has its own permission, which allows to select which users have the permission to select their own language, but that part is not strictly necessary.

I used hook_init() because the documentation for hook_user_load() has the following warning:

  Due to the static cache in user_load_multiple() you should not use this hook to modify the user properties returned by the {users} table itself since this may result in unreliable results when loading from cache.

The code is also changing on the fly a property for the currently logged-in user, without making any changes in the database. hook_user_load() would not serve this purpose, since it is invoked any time a module calls user_load().


What you need to do, is to subclass the handler(s) and add the methods you want to overwrite or change. Then you need to replace the normal handlers with your custom create handler(s) wherever you need this, in hook_views_data_alter.


Same module for different Drupal versions

Sorry, you can't without hacking Drupal's core. By the documentation for Drupal 7 you need to set:

core = 7.x

in module's info file. At the same time documentation for Drupal 6 requires you to set:

core = 6.x

Values without [] may appear only once, so you cannot write:

core = 6.x
core = 7.x

And you cannot make a value to be an array, so following also would not be recognized and accepted:

core[] = 6.x
core[] = 7.x

Safest way to solve it is to keep modules separate, and move common PHP code to a PHP library. With Libraries API it should be pretty easy to do.


Drupal 7.2: Horizontal & Vertical Tabs- HOW?

The best solution is using the Quick Tabs module. It allows you to create static or dynamic Ajax loaded tabs with nodes, blocks, and views.


Add a module, give it a libraries file (MODULE.libraries.yml):

global:
  js:
    /js.js: {}
  css:
    theme:
      /css.css: {}

In the .module file, implement hook_page_attachments:

function MODULE_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'MODULE/global';
}

When you enable the module (or clear cache if it's an existing module), the CSS and JS will be included on every page.


How to create and check block revisions?

The revisions checkbox on blocks doesn't do anything yet, in fact I think it may have been removed. Block revisioning is being proposed for Drupal 9's generic revision UI. For the latest, please see this post on Drupal.org.


How does one add revision information to custom built entities?

So far this seems to be the best example to follow/debug and learn from, others just seem to lack that crucial sentance that actually helps to see what's going on:
https://www.drupal.org/project/typical_entity_example

Use typical_entity_example_5 and note the work on .install and .module.
The key elements are in hook_entity_info (.module)/ hook_schema (.install) and the typical_entity_example_5_form_submit(...) (.admin.inc) function where we have:

$entity = $form_state['typical_entity_example_5'];
entity_form_submit_build_entity('typical_entity_example_5', $entity, $form, $form_state);
$entity->is_new_revision = TRUE;
$wrapper = entity_metadata_wrapper('typical_entity_example_5', $entity);
$wrapper->save();

The power of this example is that the form of the schemas are more or less the same, but with differences in the columns used as primary keys.

I'm still trying to work out though whether it's better to have it in ->save() rather than using it in the admin form submit as above. So that any and every save invocation creates a new entity. Programmatical (non aforementioned admin UI) editing of an entity would presumably not create a new revision unless manually coded in.

NOTE: you can put it in either the custom entity class:

class YourClass extends Entity {
    public function save() {
        $this->is_new_revision = TRUE;
        parent::save();
    }
}

or custom controller:

class YourClassController extends EntityAPIController {
    public function save($entity, $transaction = NULL) {
        $entity->is_new_revision = TRUE;
        return parent::save($entity, $transaction);
    }
}

Or both, I guess. I'm still not 100% sure if there are use cases which neglect one way or another as from what I've seen so far it goes YourClass->save() >> into >> YourClassController->save() so I suppose I'll probably just put it in both just to be sure...


How to create a rule that grants user points after a user passed a quiz?

If using Quiz 7.x-5.x

Assuming you're using the 7.x-5.x version of the Quiz module, you can take advantage of integration with the Rules module that this new release comes with.

To do so, you can start from the delivered rule, which looks like so:

{ "rules_send_results_at_the_end_of_a_quiz" : {
    "LABEL" : "Send quiz results at the end of a quiz",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "quiz_result_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "quiz-result-unchanged:is-evaluated" ], "value" : "0" } },
      { "data_is" : { "data" : [ "quiz-result:is-evaluated" ], "value" : "1" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "quiz-result:uid:mail" ],
          "subject" : "[site:name]: Your results for [quiz-result:nid:title]",
          "message" : "[quiz-result:uid:name],\r\n\r\nYou finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nYour score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz-results\/[quiz-result:result-id]",
          "language" : [ "" ]
        }
      },
      { "mail" : {
          "to" : [ "quiz-result:nid:author:mail" ],
          "subject" : "[site:name]: [quiz-result:uid:name]\u0027s results for [quiz-result:nid:title]",
          "message" : "[quiz-result:nid:author:name],\r\n\r\n[quiz-result:uid:name] finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nTheir score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz\/results\/[quiz-result:result-id]\/view",
          "language" : [ "" ]
        }
      }
    ]
  }
}

After you enable Rules (and Rules UI, a submodule of it), just clone the above rule (using the Rules UI) and apply these changes:

Add these extra Rules Conditions:

entity is of type (to make the data about the Quiz node available, such as pass rate).
verify if the user taking the Quiz actually passed.

Add another Rules Action to grant an amount of User Points that you may want to be related to [quiz-result:score] (note that this token is also shown in the Rules example above, within the Rules Action), e.g. an amount that equals the score of the Quiz. If you're not familiar with how to use Rules to grant user points, then have a look at the answer to "How to grant userpoints only for modifying nodes last changed at least 20 days ago?" (which also includes a Rules example to make that happen).

After you added this extra Rules Condition and Rules Action, your rule should look similar to this rule:

{ "rules_send_results_at_the_end_of_a_quiz" : {
    "LABEL" : "Send quiz results at the end of a quiz",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "userpoints_rules", "entity" ],
    "ON" : { "quiz_result_update" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "quiz-result:nid" ], "type" : "node" } },
      { "data_is" : { "data" : [ "quiz-result-unchanged:is-evaluated" ], "value" : "0" } },
      { "data_is" : { "data" : [ "quiz-result:is-evaluated" ], "value" : "1" } },
      { "NOT data_is" : {
          "data" : [ "quiz-result:score" ],
          "op" : "\u003C",
          "value" : [ "quiz-result:nid:quiz:pass-rate" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "quiz-result:uid:mail" ],
          "subject" : "[site:name]: Your results for [quiz-result:nid:title]",
          "message" : "[quiz-result:uid:name],\r\n\r\nYou finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nYour score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz-results\/[quiz-result:result-id]",
          "language" : [ "" ]
        }
      },
      { "mail" : {
          "to" : [ "quiz-result:nid:author:mail" ],
          "subject" : "[site:name]: [quiz-result:uid:name]\u0027s results for [quiz-result:nid:title]",
          "message" : "[quiz-result:nid:author:name],\r\n\r\n[quiz-result:uid:name] finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nTheir score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz\/results\/[quiz-result:result-id]\/view",
          "language" : [ "" ]
        }
      },
      { "drupal_message" : { "message" : "Congratulations, you passed this quiz with a score of [quiz-result:score] % ..." } },
      { "userpoints_action_grant_points" : {
          "user" : [ "quiz-result:uid" ],
          "points" : [ "quiz-result:score" ],
          "tid" : "0",
          "entity" : [ "quiz-result" ],
          "description" : "Points earned because of your results in the quiz.",
          "operation" : "Insert",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

Just use the Rules UI to import the above rule and you should (more or less) be ready to go. Possibly the only remaining tuning you want to do in this rule is like so:

Review the various settings of the Rules Action to grant User Points (eg the amount (= quiz-result:score in the rule above), the description and the category for the points.
Optionally also review the messages being shown when a user passes a quiz. Using the above rule, you'll get a messages similar to this example:

  Congratulations, you passed this quiz with a score of 80 % ...

That message is also followed by a related message produced by the User Points module, which looks like in this example:

  You just earned 80 points and now have 29.512 points in the General category.

Attention: be aware that the above rule will grant user points over and over again, since there is no validation (Rules Condition) if the user taking the quiz already passed the quiz before. If you also want to get that resolve (= only grant such points once), then refer to my answer to "How to check if user has passed the quiz already before granting user points?".

If using Quiz 7.x-4.x

For the 7.x-4.x version of the Quiz module, you may want to try the patch from fago (aka the Rules maestro ...), attached to issue # 1300420, which has a description like so (note the last phrase in it ...):

  ... adds basic rules integration to quiz. It includes an event when users have finished taking a quiz, a condition to check whether a user has passed a certain quiz and an action to clear quiz results for a user.

  Patch works for me.


When using drupal_add_js with the 'setting' option, do the set variables apply for all users?

Assuming that custom_get_username_function() returns a different username for each of the logged-in users, then that code will pass to JavaScript a different and a single username for each user. There could be 4 different logged-in user, but each user gets one username, assuming custom_get_username_function() is using the currently logged-in user ID to retrieve the username.

I would rather not add JavaScript code from a form submission handler; if I need to add it, I would add it to the form, or to the page where the users are redirected after they submit the form.


User profile fields: Get count of fields with value XYZ

You can create a view as a block using users as the base table (Structure>Views>Add View and set show=Users and check "Create a Block").  Then turn aggregation on in the advanced settings. Then add the field_category field and select "Group Field". Next add field_category a second time and select "Count". This should give you a column of each category, and the count of how many users exist in each category.

Finally, add the block to the frontpage in the Block Layout.


I had the same requirement a few time ago.You are right the key is date pager in url to navigate through date/month/year

here is a workaround I did,might be helpfull in your case too.

As in brief I created custom form with field as month and year.Submission of the form navigates passing the selected month and year in url using drupal_goto() and we are calling this form in views header.


Adding child elements to checkbox/radio form elements

I don't believe you can make a radio button a "parent".

Here's an example of using radios, checkboxes, and fieldsets.

http://api.drupal.org/api/examples/form_example!form_example_states.inc/function/form_example_states_form/7

You might take a look at http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#container

Try removing search_attributes from search_product

$form['search_attributes'] = array(
    '#type' => 'checkboxes',
    '#options' => array(
        'name' => t('by Name'),
        'model' => t('by Model'),
        'catalog_no' => t('by Catalogue No.'),
        'manufacturer' => t('by Manufacturer'),
        'description' => t('by Description'),
    ),
);


Can't uninstall module that depends on custom field type in use

If a module define a field type, it can't be uninstalled if you have a field of this type. This is not related which tables are in the database, and deleting tables in the database wont resolve this.

What you need to do, is to delete the field yourself. Drupal doesn't want to this automatically, as it could mean data loss. From the message you get the field name taxonomy_term.field_yoast_seo. This machine name is structured as ENTITY_TYPE.FIELD_NAME, so the field you need to delete is on a taxonomy term. It doesn't tell which vocabulary it's located on, but hopefully you can find it manually and resolve it


Preview image after uploading using Form API

Define the theme in the field, and simulate the code structure to preview the image that you just upload. My solution is as follows,

$form['abc_field']['abc_filename'] = array(
        '#type' => 'managed_file',
        '#title' => t('abc image'),
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            'file_validate_size' => array(1 * 1024 * 1024),
        ),
        '#theme' => 'abc_thumb_upload',
        '#upload_location' => 'public://abc/'
    );

In your hook_theme(),

return array(
    'abc_thumb_upload' => array(
        'render element' => 'element',
        'file'           => 'abc.module',
));

In your theme_abc_thumb_upload(),

function theme_abc_thumb_upload($variables) {

    $element = $variables['element'];

    if (isset($element['#file']->uri)) {
        $output = '

';
        $output .= 'uri) . '" />';
        $output .= '<input type="submit" id="edit-' . $element['#name'] . '-remove-button" name="' . $element['#name'] . '_remove_button" value="Remove" class="form-submit ajax-processed">';
        $output .= '<input type="hidden" name="' . $element['#name'] . '[fid]" value="' . $element['#file']->fid . '">';

        return $output;
    }
}


Add a MAX aggregation function to a query

In your case, the code should be something similar to the following one:

$query = db_select('node', 'n')->groupBy('title');
$query->addExpression('MAX(nid)', 'max_nid');

You don't use $query = new db_select('node', 'n'); db_select() already returns an object. If you want to clone that object, you should not invoke new on it.

$query->addExpression() returns the alias currently used for the expression you add; it is normally the same alias passed to the method, but it can be different if the alias is already used. In this case, the alias is max_nid if max_nid is not already used, or max_nid_N if the alias is already used; N is an integer that is added to make the alias unique.
Using the alias returned from $query->addExpression() is important when a function is altering a query passed from other functions, such as in the case of a query passed to a hook. In this specific case it is not necessary, as the function that is calling db_select() is also adding the expression.


How do I create a role-specific registration page?

I suggest you to try the Multiple Registration module (https://www.drupal.org/project/multiple_registration), since this is precisely what it does "adds ability to create role-specific registration pages."

And as for the need to add the "admin approval" functionality, too, for specific user roles on your site, I would recommend you the Registration Role with Approval module (https://www.drupal.org/project/registration_role_with_approval)

Also, see if you will find this post of any help: https://www.optasy.com/blog/how-create-role-specific-user-registration-forms-drupal

Good luck!


Get select options for an entityreference field using another field as a contextual filter?

I've kept an eye out for a module that does this since the original post, but never came up with anything. I've been using a sort of "one off" solution to do this on a case-by-case basis instead:

In a custom module, implement hook_form_FORM_ID_alter() for the
form with your dynamic fields.
Add #ajax attributes to the first element to trigger and handle
changes to it with AJAX. This will specify the AJAX callback handler
and the HTML ID of the element to be replaced with the AJAX response.
In the ajax callback for that element, use the AJAX-submitted value
to dynamically get the appropriate values for the second value. For
me, this is usually a query of some sort with the submitted value as
a filter.
Update the second field's form element #options attribute with the
dynamic values and return the element.


How do I migrate the "Created" and "Modified" date fields?

Turns out that for created & changed dates, they are stored differently than field_date's, you must convert these to Unix universal time.

  changed:
    plugin: format_date
    source: update
    from_format: 'm/d/Y'
    to_format: 'U'
    from_timezone: 'UTC'
    to_timezone: 'UTC'
  created:
    plugin: format_date
    source: DateCreated
    from_format: 'm/d/Y'
    to_format: 'U'
    from_timezone: 'UTC'
    to_timezone: 'UTC'


I solved this by linking to the correct path where the composer was placed (as suggested by Japo).

EDIT:

In another server setup, the same issue was fixed by adding php-curl module.


Custom validation for a custom field in comment form

Assuming the field is a text type (and your site is monolingual) you'll find the value here:

$form_state['values']['field_website'][LANGUAGE_NONE][0]['value']

There's an explanation here.

Instead of doing this, though, you might want to have a look at the Field Validation module, which will let you add the same validation rule through the UI.


http://drupal.org/project/pathauto

this module do what you want ... this module generate url automatically depending on the node title... and you can add prefix or suffix to the automatic url path that generated by this module

if you are using drupal 6 then you can configure this module from

http://yoursite.com/admin/build/path/pathauto


How to add a button to a custom table that opens a form in a new tab and automatically fills out with data from that table

Prepopulate module can pass value to form with query parameter.

Simple example:

New form';

More examples can be found on its documentation.

If you find problems, please check this issue, some known bug has been introduced from 7.x-2.1 version. You may need to patch it.


Organic Groups Support for Context Module

Have you read this article? http://drupalconnect.com/blog/creating-drupal-context-plugins

I think it can help you to build you own module to use with context.

Oskar


In this context, the English verbs "flush" and "clear" are equivalent.

However, I've never seen a command named "flush cache" in Drupal 7.  Not having seen the video tutorial you mention, it is impossible to tell what was ment.  In the standard GUI, the button "Clear all caches" (under Home » Administration » Configuration » Development » Clear cache) is (AFAIK) the only way to do it.

If you have Drush installed, you can do more or less the same thing using the CLI with the following command:

drush cache-clear all

The difference is that the command drush cache-clear all also clear its internal cache, and there may be subtle differences because the drush user and web-server user are different, and may therefore interact different with file permissions to caches in the file system, such as the css registry.

However, Drush also allows you to make more targeted cache clears, see: Making Targeted Drupal Cache Clears using Drush.


Best approach to create a troubleshouting section?

If you go down the book route then you can always use the flag module for the "Was this information helpful".

There is also the FAQ module which doesn't quite fit your use case but might be worth checking out just in case.


Yes,
It's safe to remove comment body from the type of node you have created.
One may turn off the comments settings from content-type settings.


You can use page arguments:

function MYMODULE_menu() {
  $items['foo'] = array(
    'title' => 'Bar',
    'access arguments' => array('access content'),
    'page callback' => 'MYMODULE_baz',
    'page arguments' => array('http://google.com', 'another arg'),
  );

  return $items;
}

function MYMODULE_baz($url, $another_arg) {
  // Do something with $url, e.g. redirect.
  drupal_goto($url);
}

That's quite a contrived example, if you are redirecting, you could shorten that by just using drupal_goto as the callback:

function MYMODULE_menu() {
  $items['foo'] = array(
    'title' => 'Bar',
    'access arguments' => array('access content'),
    'page callback' => 'drupal_goto',
    'page arguments' => array('http://google.com'),
  );

  return $items;
}


You have to install the Context module and make sure the the Date Views and Date Context modules are also enabled. Then your date fields will appear in the format:

Field: Date (field_machine_name)

Contextual filters based on these fields have the same formatting options as those based on node creation date.


If you can shell into the account, you

cd /var/www/somewhere/docroot/sites/all/module
patch -p1 < /path/to/the/patchfile

Depending on how the patch was rolled, you may need to adjust the number after the -p to get it to apply properly.  The man page can give you more details.

If you can't shell into the host, then you need to downloads the files(s), apply the patch locally and then upload them.  This question give guidance, or you can cut to the chase and check out TortoiseMerge.


Hook name in module doesn't seem to work

there is no hook_buildForm() hook in Drupal. The hook you are trying to implement is hook_civicrm_buildForm(), so to get it work you should use mymodule_civicrm_buildForm().
You can always use hook_form_alter() or, more specifically, hook_form_FORM_ID_alter() to make changes on any Drupal form.


Adding conditional statements as Math expression to custom text fields in views

Well you can override any of the output you have from views with a template override.
Goto your Views > Display
on the right hand side in the box labelled 'other'

click on information next to 'theme'

This will give you a list of template pages you can use to over write the section you need.  A little trial and error maybe needed at first until you get used to what your being presented.

on the left hand side of the page suggested you have a link to the code you need to use.  Copy that code and paste it into the file name your targetting ( ie views-view-field--default.tpl.php ) and add in the theme/templates  folder your using.
from here on you can manipulate the code how you want using php

Hope this makes sense, as I wrote it real quick :)


missed value in href.  replace below code.

<a href="/node/<?php print $node->nid; ?>">Lorem ipsum dolor sit amet, consectetur adipiscing elit.


How to autoupdate quiz question to newest version?

According to the issue queue its says that the update issues only happen when manual revisioning is enabled. You can find out more here: https://www.drupal.org/node/1652936
Also make sure to update to latest version and run update scripts.


Why does legend not appear when the first bar value is zero?

I would check the results you'd get by using either of these special settings in the SVG Graph library:

Use the (boolean) force_associate option.
Set the axis_min_v option to something like -1.

If none of these options help, you might have discovered "some issue" (bug?) in the SVG Graph library.

A possible work around might also be that you can think of a way to replace the "zero or null" with "NULL".


trigger in rules a beep sound on user side (current user is working)

In order to send a message to users other than the current user, you will need to do some additional processing. drupal_set_message sets a message in the current user session. It does not set a message in another user's session.

Some possible approaches include a push or pull notification type system.
For example, the server can push updates to the client using something interesting like a Service Worker (advanced). Alternatively, the client can poll the server periodically, via ajax type request to get message updates.


When Num of Values is "Unlimited", create begins with two instances

I'll post my work around just in case anyone else has the same problem.  But after fiddling around with it, I found out that if you have default values set, then it will set the first instance of the field to the default values and the second instance of the field to blank (I tested this by switching my select to textfield and if defaults were blank then I got only one instance of the field, if I put any text into the default, then I got two).  Because my fields uses a select form then I, by default, had set my field values to something, thus, I had default values, thus, it showed the behavior I mentioned.

I set 'default value' => FIELD_BEHAVIOR_NONE, in the hook_field_widget_info and the field only produced one instance.  Ridiculous.


$form_state->set(), $form_state->setValue() doesn't save new value

I assume with code works you mean you get the updated title value. Then another submit handler has already transferred the values to the entity and your changes to $form_state are too late.
So you can try to position your submit handler first:
array_unshift($form['#submit'], 'myforms_extra_submit_handler');

or update the entity instead of $form_state:
$entity = $form_state->getFormObject()->getEntity();
$title = $entity->get('title')->value;
$entity->set('title', $title . $date);

Caveat: Normally submit handlers in entity forms are attached to submit buttons. So you might want to check first all submit handlers which are active in the form before you decide where to place your submit handler.

Different approach
You are asking why your submit handler is not working and there is definitely a solution for that, but there is probably a much easier solution outside of the form when the form is trying to save the entity. See  Programmatically update a field's value


Don't modify the config table. Export the config, delete the yaml file and import the config again.

From the command line you can delete configuration items with drush:

drush config:delete core.base_field_override.node.[content-type].status


Devel is super useful to help you figure out these type of things.

Once enabled, you can write dpm($product_id) and it will print out a nice organized structure of the array.  From there, you can click on any item and it will show you how you can access the item like ['und'][0]['product_id'] in your example.

Depending on what exactly you're trying to do, there may be different ways to get the info you need.


How to display a block for some paths but not if they match some other path also?

The block control for "Show block on specific pages" supports wildcards and should work here, iirc.

Show only on these pages:

/chapters/university-of-florida/classrooms/*


Adding attributes with hook_node_view_alter

The class property is an array so you need to initialise it like this:

$build['links']['comment']['#links']['comment-add']['attributes']['class'] = array(
  'nice',
  'small',
  'radius',
  'blue',
  'button'
);


in drupal 7, views_get_view('VIEWNAME') get a error?

Even thought the documentation for views_get_view() refers to $name as the name of the view, what the function wants is the machine name of the view.

You should always check the value returned from the function is not NULL, as the function doesn't return any value, if it doesn't find the view with that name.

  ctools_include('export');
  $view = ctools_export_crud_load('views_view', $name);
  if ($view) {
    $view->update();
    return $view->clone_view();
  }

views_embed_view(), for example, uses the following code.

  $view = views_get_view($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return $view->preview($display_id, $args);

You should use similar code, avoiding to call $view->access() if the view should always be visible, independently from the permission the currently logged-in user has. If you need to show the view only when the user has the permission to see it, then you should consider using views_embed_view().


After looking around the code I ended up the _block_load_blocks function. Before calling drupal_alter('block_list', $block_info); I had 6 elements in $block_info. After the function had run I had 2 items.

Doing some digging in drupal_alter I fount out what modules were touching $block_info. The domain module was removing the blocks.

Looking at the settings on the block page I did not have my domain ticked. The message under the domain options did say:

  Limit block display to these affiliates. This block is visible on all
  domains by default using this theme.

So thought the block would appear by default. This was not the case.


How to customize the homepage title without creating new pages?

By default the homepage for D8 is set to /node (similar to D7).
And unlike Drupal 7, this is a view. So, adding a title is as simple as adding the title to the view. (Views in core, yay!)

Go to /admin/structure/views/view/frontpage.
Add title to the view
Save

It is as simple as that!
If you save any other page as your homepage, then you could set the title to the route as you have already specified in the question.


adding multiple content elements to a page?

It seems you are looking for https://drupal.org/project/panels. It gives you the ability to add various types of content.


Changing the order used to show the weekdays

Hopefully that module integrates with the rest of the system properly - if it does, you can go to /admin/config/regional/settings and change "First day of week" to Monday.


Populate a field with the sum of two fields while content creation

Sounds liks a job for Computed Field

  Computed Field is a very powerful CCK field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code. You may draw
  on anything available to Drupal, including other fields, the current
  user, database tables, you name it.

You should just be able to set the field value literally as in your example (i.e. field = fieldA + fieldB)


How to filter groups of paired values in Views

I am not able to reproduce the behavior you describe. In configuring a Field Collections and Views in the way you describe I do get the desired results.

Here is a screenshot of my configuration:

And here are the results:

And here is the filtering:

By letter:

By number:

Mismatched letter/number yields no results:

And here is the full View export:

$view = new view();
$view->name = 'stacktest_fieldcollection';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'stacktest_fieldcollection';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'stacktest_fieldcollection';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: Content: FC (field_fc) */
$handler->display->display_options['relationships']['field_fc_value']['id'] = 'field_fc_value';
$handler->display->display_options['relationships']['field_fc_value']['table'] = 'field_data_field_fc';
$handler->display->display_options['relationships']['field_fc_value']['field'] = 'field_fc_value';
$handler->display->display_options['relationships']['field_fc_value']['required'] = TRUE;
$handler->display->display_options['relationships']['field_fc_value']['delta'] = '-1';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Field collection item: Letter */
$handler->display->display_options['fields']['field_letter']['id'] = 'field_letter';
$handler->display->display_options['fields']['field_letter']['table'] = 'field_data_field_letter';
$handler->display->display_options['fields']['field_letter']['field'] = 'field_letter';
$handler->display->display_options['fields']['field_letter']['relationship'] = 'field_fc_value';
/* Field: Field collection item: Number */
$handler->display->display_options['fields']['field_number']['id'] = 'field_number';
$handler->display->display_options['fields']['field_number']['table'] = 'field_data_field_number';
$handler->display->display_options['fields']['field_number']['field'] = 'field_number';
$handler->display->display_options['fields']['field_number']['relationship'] = 'field_fc_value';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
/* Contextual filter: Field collection item: Letter (field_letter) */
$handler->display->display_options['arguments']['field_letter_value']['id'] = 'field_letter_value';
$handler->display->display_options['arguments']['field_letter_value']['table'] = 'field_data_field_letter';
$handler->display->display_options['arguments']['field_letter_value']['field'] = 'field_letter_value';
$handler->display->display_options['arguments']['field_letter_value']['relationship'] = 'field_fc_value';
$handler->display->display_options['arguments']['field_letter_value']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['field_letter_value']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_letter_value']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_letter_value']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['field_letter_value']['limit'] = '0';
/* Contextual filter: Field collection item: Number (field_number) */
$handler->display->display_options['arguments']['field_number_value']['id'] = 'field_number_value';
$handler->display->display_options['arguments']['field_number_value']['table'] = 'field_data_field_number';
$handler->display->display_options['arguments']['field_number_value']['field'] = 'field_number_value';
$handler->display->display_options['arguments']['field_number_value']['relationship'] = 'field_fc_value';
$handler->display->display_options['arguments']['field_number_value']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['field_number_value']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_number_value']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_number_value']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['field_number_value']['limit'] = '0';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'stacktest-fieldcollection';


I've defined the block view. When I change the selected option, the log gets two errors.

It seems the error happens after you submitting the block. So the file loads fine on view, but not when the form is processed which should have information where to look for it.

So you should define your form using hook_forms.

  By default, when drupal_get_form() is called, the system will look for a function with the same name as the form ID, and use that function to build the form. If no such function is found, Drupal calls this hook.

Also, when you working with the forms, instead of drupal_get_form($form_id), you can consider using form_load_include() to make sure the include file is loaded whenever the form is processed.

  Use this function instead of module_load_include() from inside a form constructor or any form processing logic as it ensures that the include file is loaded whenever the form is processed. In contrast to using module_load_include() directly, form_load_include() makes sure the include file is correctly loaded also if the form is cached.


The pre-render function for a 'link' element type is drupal_pre_render_link()...looking at the docs, you can pass these parameters:

#title: The link text to pass as argument to l().
#href: The URL path component to pass as argument to l().
#options: (optional) An array of options to pass to l().

You can force a link prepared through l() to display HTML by passing 'html' => TRUE as an option, so you should be able to do the same through the render array:

$image = theme('image', array('path' => 'images/link1img.png'));

$link = array(
  '#type'    => 'link',
  '#title'   => $image,
  '#href'    => 'http://www.link1.example',
  '#options' => array('html' => TRUE, 'title' => 'link1'),
  '#suffix'  => '<br />',
);


Rules help: After updating existing content

For your task you need site:current-user token which corresponds to $GLOBALS['user'] (global $user) object.

  I'm not sure how reliable this is when multiple users are logged in to the system?

Webserver creates new PHP thread (or process) for each request so there are no sharing variables between requests.global $user variable is initialized by Drupal on every request.

When you have just updated a node you can use global $user to know who updated this node. At any time after updating you can get that user id from revision ($node->revision_uid).


Fatal error: Call to undefined function node_type_get_names() Drupal 7.59

Can't comment but I don't see the Node module. Its part of the core and should be present(thats where the missing function is defined). Verify that the module is present and permissions are set right


Organic Groups - Display the Group Name that a peice of content belongs to

Found the answer with the help of this post: Using Views to List a Member's Organic Groups (7.x-2.3)

Here is a screeshot of my view: http://cl.ly/image/2O1h1x3T3J43

by adding the relationship: "OG Membership: Group Node from OG membership" I was able to use that relationship in a new title field and display.


How to inject the database connection into a custom service?

You can't inject Drupal\Core\Database\Database, it's a container of static functions, constants, & variables for core database functions.

If you'd like to inject the Connection object, that is be possible, and is more like something you want (unless you have scenario where  setting.php is dynamic an all possible values of $schema can't be known).

You can follow the example Drupal sets with the default @database class in core.services.yml:

  database:
    class: Drupal\Core\Database\Connection
    factory: Drupal\Core\Database\Database::getConnection
    arguments: [default]

In your mymodule.services.yml you can define the factory/arguments for each database connection you have, plus your DataAccess service class with the injected connections.

services:
  mymodule.database_schema:
    class: Drupal\Core\Database\Connection
    factory: Drupal\Core\Database\Database::getConnection
    arguments: [default, schema]
  mymodule.database_schema2:
    class: Drupal\Core\Database\Connection
    factory: Drupal\Core\Database\Database::getConnection
    arguments: [default, schema2]
  mymodule.data_access:
    class: Drupal\mymodule\DataAccess
    arguments: ['@mymodule.database_schema', '@mymodule.database_schema2']

From there you can store the database connections in DataAccess's constructor and reference them as required by DataAccess's methods.


Can we create a feature for the changes in webform by using feature module?

Features does not give you the power to import/export the webform created.

You could use the Webform Share module.

For more details you could read the README.txt file of this module.


I prefer to use drush from drush alias files, so that the magic of Drush figuring out everything from the document root isn't so magical and you can sometimes more easily debug issues from a proper drush alias file.

As others mention it's likely the database connection that's not working. In docker you can use the --add-host build option, or the extra_hosts docker-compose options to give a name to your database container (docker can use the container name to properly create the /etc/hosts entry at runtime).

See this stackexchange answer https://stackoverflow.com/a/38306666/1491507

By following the above directions in docker-compose an entry such as the following that creates a named hosted in /etc/hosts as my_resolved_db_service which is magically resolved to the mariadb container.

extra_hosts:
  - "my_resolved_db_service:mariadb"

Then in a drush alias file, or when installing drupal via drush you would use the /etc/host name created:
drush si --db-url=mysql://root:root@my_resolved_db_service/drupal as an example.


Several NFS folders for one Drupal instance

ini_set('opcache.validate_timestamps', FALSE);

Then when you want to push a code change out run

opcache_reset();

or restart the Apache process.

If you're working on a set of files you can use opcache_invalidate() to check if those files need to be recompiled.

// http://stackoverflow.com/questions/24783862/php-recursively-list-all-files-in-directory
function get_dir_contents($dir, &$results = array()){
  $files = scandir($dir);

  foreach($files as $key => $value){
    $path = realpath($dir. DIRECTORY_SEPARATOR. $value);
    if (!is_dir($path)) {
      $results[] = $path;
    }
    elseif (is_dir($path) && $value != "." && $value != "..") {
      get_dir_contents($path, $results);
      $results[] = $path;
    }
  }

  return $results;
}

// https://api.drupal.org/api/drupal/core!lib!Drupal!Component!Utility!OpCodeCache.php/function/OpCodeCache%3A%3Ainvalidate/8
function invalidate_opcodecache($pathname) {
  clearstatcache(TRUE, $pathname);

  // Check if the Zend OPcache is enabled and if so invalidate the file.
  if (function_exists('opcache_invalidate')) {
    opcache_invalidate($pathname, TRUE);
  }
  // If apcu extension is enabled in PHP 5.5 or greater it emulates apc.
  // This is to provide an easy upgrade path if you are using apc's user
  // caching however the emulation does not extend to opcode caching.
  // Therefore we need to check if the function exists as well.
  if (extension_loaded('apc') && function_exists('apc_delete_file')) {
    // apc_delete_file() throws a PHP warning in case the specified file was
    // not compiled yet.
    // @see http://php.net/manual/en/function.apc-delete-file.php
    @apc_delete_file($pathname);
  }
}

$file_path = 'sites/all/modules/custom';
$files = get_dir_contents($file_path);
foreach ($files as $pathname) {
  invalidate_opcodecache($pathname);
}
$file_path = 'sites/all/themes/custom';
$files = get_dir_contents($file_path);
foreach ($files as $pathname) {
  invalidate_opcodecache($pathname);
}

Put this code in your settings.php file.

If using APC the info for that is located here: Best APC settings to reduce page execution time

And apache: Adding .htaccess within httpd.conf correctly

Also see: First page load/execution slow, login slower Drupal 7


How to bulk/mass import/create webform components?

Maybe the Webform Share module can solve your problem?


You can create a view with webform type. Then add a Global PHP field in header.

<?php
$nid=62;
$option1_count=0;
$option2_count=0;
foreach($results as $results1) {
    $each_submission=webform_get_submission($nid, $results1->sid);
    //print_r($each_submission->data);
    if($each_submission->data[1][0]==1) {
        $option1_count++;
    }
    if($each_submission->data[1][0]==2) {
        $option2_count++;
    }
}
$top=[$option1_count,$option2_count];
arsort($top);
?>

I haven't tested this code but something like this should work.

EDIT:

You can make that code generic but if you don't want that then use grouping and aggregation in views and try Views Distinct

First add field Webform submission data:Value(your webform field) and set aggregation to yes. This will help.


MigrateSQLMap with multiple same-name source keys?

I'm not aware of a solution without altering the source database -- although there are in my opinion clean ways of altering the source DB; and it's not a ton of code:

In either your migration module hook_install() function or a pre/post Import hook call (https://drupal.org/node/1343112) simply using a custom db_query() such as:

db_query("CREATE TABLE foo LIKE other_table; INSERT INTO foo FROM (intersection query); ALTER TABLE foo (change id to type_id);");

You can drop/recreate the table as apart of a pre/post import call.

You just have to get the SQL right and it's all of 3 SQL statements, and 1 or 2 Drupal hook functions to make it all repeatable using Migrations.


try:

t("F !bullet", array("!bullet" => "&#8226;"));
t("P !bullet", array("!bullet" => "&#8226;"));

Drupal escapes any characters passed through t() function so you need to use variables like this:

@variable: Escaped to HTML using check_plain(). Use this as the
default choice for anything displayed on a page on the site.
%variable: Escaped to HTML and formatted using drupal_placeholder(),
which makes it display as emphasized text.
!variable: Inserted as is, with no sanitization or formatting. Only
use this for text that has already been prepared for HTML display
(for example, user-supplied text that has already been run through
check_plain() previously, or is expected to contain some limited HTML
tags and has already been run through filter_xss() previously).


GTM container in block appears as regular text even though set to be Full-HTML

I've discovered that CKeditor made the code <p> so I tried to replace the <p> tag of the input to  but it didn't help, so as alternative I tried to format the input as with PHP text-foramt, But this also didn't help.

Working solutions would be:

Putting the code somewhere (at the first row for example) of you page.tpl.php.
Installing the module.

If you plan to change your sites theme and going to change some themes in the near future, better pick option 2 --- It will save you from copying the code time and again to each new page.tpl.php.


You can read a little bit more info in the Description text: A bridge to the Content entity that is referenced via field_entityref so if you're using different fields you can discern them by the field machine name.

Your theme seems to have the Description text hidden behind an icon. Can you see it when you click on the icon?


How to force openid login from a single provider in Drupal 7?

You must create a custom module to generate a page "/login" that start OpenID authenticate.

Create a module with this code :

/**
 * Implements hook_menu().
 */
function mymodule_menu() {

  $items['login'] = array(
    'title' => 'OpenID Login',
    'page callback' => 'openid_login',
    'access callback' => 'user_is_anonymous',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/*
 * Menu callback; start openid authenticate
 */
function mymodule_login() {

  $return_to = url('openid/authenticate', array('absolute' => TRUE, 'query' => array('destination' => 'user')));

  openid_begin("https://www.myopenid.com/", $return_to, array());
}

The example works with the myopenid.com provider.
Go to "/login" on your website to log in.


How can I get field labels from submission data?

I assume that you pass $form, and $form_state into your custom handler function. You can always access your webform field "label" via $form variable.

Try kint() or dd() $form['elements'] on specific form and go into depth to find your field, then you can easily get $form['elements']['my_field_name']['#title'] etc.


Error: Class 'Drupal' not found in bootstrap.inc

Drush 6.x only works with Drupal 6 or 7, upgrade to Drush 7.x.

Source


How to add product display nid to user order view?

You can use the module commerce_product_attributes to show more product details on the line item.

  Attribute field for line item: This field allows the presentation of
  the product in the shopping cart by a separated view mode. A new
  product display is added. There you can define the fields which should
  be displayed for this product type in the shopping cart.

While it can be used on the shopping cart, it can also be used on the Orders view.


What are the array keys of $content that can be hidden?

Yes, it is dynamical, all modules can add new elements.

Install http://drupal.org/project/devel and then use dpm($content); Note that when you do this inside a page, you will probably only see it after another reload.


Upgrading drupal 8 beta3 to beta4 table user__roles not exists

There is no upgrade path yet.

You could try to alter the table manually, or copy it from a new install, but you will very likely run into other issues as well.


Is it ever okay to ignore a warning about an inconsistent Database schema?

It could be okay, for a time, until the module that has an out of date schema attempts to read, save, update, or delete data from an out-of-date database table. At that point, you'd get inconsistent data in your database at least, and possibly end up with a corrupted database or have your site return the WSOD (white screen of death) at worst.

The warning simply means there is at least one update that hasn't yet been run. It's always a good idea to run updates by visiting update.php or using drush updatedb whenever you update any modules or Drupal core.


Get value of field attached to the file entity in a view

You should just need to add a relationship with your file field, then the fields on your file entity should be available when adding fields to your view.


Drupal commerce - what page/function should i call after an off site payment

i used those two

// Return to the previous page when payment is canceled
'cancel_return' => url('checkout/' . $order->order_id . '/payment/back/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),

// Return to the payment redirect page for processing successful payments
'return' => url('checkout/' . $order->order_id . '/payment/return/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),

but also have an IPN. (your NOTIFICATION_URL)

don't forget to create a commerce transaction with the feedback from the carrier !

maybe have a look at another module, like postfinance (by me),
or paypal (by Ryan - the commerce god ;))


How can I know if a type of content is moderated?

You should be able to get that from ModerationInformation:: shouldModerateEntitiesOfBundle(), via the content_moderation.moderation_information service:

$moderation_info = \Drupal::service('content_moderation.moderation_information');
$entity_type = \Drupal::entityTypeManager()->getDefinition('node');
if ($moderation_info->shouldModerateEntitiesOfBundle($entity_type, $content_type->id())) {
  // ...
}


As the top line suggests $purchased_entity is of of type "Drupal\commerce_product\Entity\ProductVariation" which is basically an entity.

All entities have a ->get('field_name') method.

So for your example to get 'field_order_no' you would do

$order_no = $purchased_entity->get('field_order_no')->getValue();

You can retrieve the value of any field via the ->getValue() method which returns an array.


Programmatically geting teaser of a field other than body

Go to your node type's display settings for the teaser view mode and verify that the field is not hidden.


Profile 2, update separate database on submit?

Every module which exposes hooks are documented in module *.api.php file. In your case it's just hook_profile2_update .

/**
* Respond to a profile being updated.
*
* This hook is invoked after the profile has been updated in the database.
*
* @param $profile
*   The $profile that is being updated.
*
* @see hook_entity_update()
*/
function hook_profile2_update($profile) {
  db_update('mytable')
    ->fields(array('extra' => $profile->extra))
    ->condition('pid', $profile->pid)
    ->execute();
}

Refer http://cgit.drupalcode.org/profile2/tree/profile2.api.php for more details.


you should merge the existing vales in $form['dropdown_second']['#options'] with the one in $form_state['values']['field_name']

something like this:

$existing_options = isset($form['dropdown_second']['#options']) ? $form['dropdown_second']['#options'] : array();
$new_option = get_dropdown_options($field_val);

$form['dropdown_second'] = array(
    '#type' => 'select',
    '#title' => 'Dynamic Dropdown',
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' => array_merge($existing_options, $new_option),
    '#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
  );


How to add button to webform to set value to a field

You will have to create a button in a

function hook_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    // Your code here.
}

and use the #ajax property of the button to update the field when the button is clicked.

The examples D7 module has some nice AJAX examples that will show you how the mechanism works.


Is it possible to have a block of content on a taxonomy term page?

One way to change the output of these pages is to use a module like Taxonomy Views Integrator. This will allow you to create any number of views for different vocabs or even specific taxonomy terms and drive the presentation of the taxonomy output. I use this regularly to override the default term page and present different layouts of content (typically powered by view modes).

Another way to approach it (creating landing pages) would be to create a content page representing that taxonomy page, then drop a TVI view block on this page under the main content. You could also use Panels to do that, but I don't use Panels, so I can't speak to that.