Find all contexts in which a block appears

You can quickly find all the contexts in which a block appears by performing a code search. Exported Contexts are placed inside name_of_your_feature.context.inc files. So when searching your Contexts for a particular block name you could restrict your search to *.context.inc files. Here's an example Zend Studio/Eclipse search as described above:

My team generally puts Features (which contain exportables such as Contexts) in their own dedicated folder, making your code search faster and more efficient.

/modules
  /contrib
  /custom
    /features


PHPUnit calling external function as object

The problem is that your use declaration is incorrect, and is causing your call to the client to look in the wrong namespace. You probably need to change this:

use cvr\src\Cvrapi\CVRClient;

To this:

use Cvrapi\CVRClient;

And change this:

$result = \Cvrapi\CVRClient::request('29910251', 'dk', 'vat', 'Unit Testing');

To this:

$result = CVRClient::request('29910251', 'dk', 'vat', 'Unit Testing');


How can I display search filters in a view?

Below are some guidelines to setting up each of your requirements in a view. Worth noting, in order to display each in the same row, you'll need to customize the view template to combine the exposed filters and the results count from the view header.

Number of Results Found

In the Header section (middle column) of the View edit page, click ADD.
If your view has multiple displays, be sure to select whether to apply this to all displays in the view, or just the selected/current one in the FOR section.
Select "Result summary" and click the ADD AND CONFIGURE HEADER button.
Edit/customize your results text with the tokens. If you want to still expose the same text pattern if no results are found, check the checkbox "Display even if view has no result"
Click APPLY

Select dropdowns to filter results by a taxonomy

In the Filter Criteria section (near bottom of left column) of the View edit page, click ADD.
If your view has multiple displays, be sure to select whether to apply this to all displays in the view, or just the selected/current one in the FOR section.
Find your custom taxonomy field you wish to filter by. Note, if your field is configured to allow multiple term selection, you'll see two instances of the field listed (the field itself, and the field delta).  Pick the field itself.
Click APPLY.
If the field is setup to allow taxonomy terms from multiple taxonomies/vocabularies, select the one you wish to show/filter on. Choose the dropdown option to set the filter as a select element.
Check the checkbox to "Expose this filter to visitors, to allow them to change it"
Select the "single filter" format and update the field label to reflect the label you'd like the user to see. Keep the operator as "is one of". In the righ column, Leave the list of terms unselected to automatically show all terms in the filter.
scroll further down the form, and click the REDUCE DUPLICATES option; optionally- click the REMEMBER THE LAST SELECTION option so that users clicking a back button to return to the page will still see the previous selection.
Finally, click apply to save the filter settings.
If the Auto preview option is enabled, you should now see the select filter in the view preview below the view config section (even if there are no results).

Free text search box

To setup a free text search box, you'll need to use the "Combine fields filter"; but it can only be applied to search the fields configured in the view. (You can add fields and exclude from display).  If your view is setup to "Show Content", you'll need to click the "Settings" for the view Format and select "Force Using Fields" to add fields to the view for filtering/searching.
Add the fields for searching (title, body, etc)
In the Filter Criteria section (near bottom of left column) of the View edit page, click ADD.
If your view has multiple displays, be sure to select whether to apply this to all displays in the view, or just the selected/current one in the FOR section.
Find and select the "Combine Fields Filter" and click APPLY.
Check the checkbox to "Expose this filter to visitors, to allow them to change it"
Select the "single filter" format and update the field label to reflect the label you'd like the user to see. Change the operator to "Contains".
scroll further down the form, and click the REDUCE DUPLICATES option; optionally- click the REMEMBER THE LAST SELECTION option so that users clicking a back button to return to the page will still see the previous selection.
scroll even further down and multiselect the applicable search fields.
Finally, click apply to save the filter settings.
If the Auto preview option is enabled, you should now see the search box in the view preview below the view config section (even if there are no results).

Customizing the View Templates

Refer to the "Understanding Views Templates" and "Naming Views Templates" sections of this blog post for a high level rundown of Drupal 8 view templating.
This legacy Views Template listing for Drupal 6 & 7 gives a good rundown of all the various views component templates (view header, view footer, view exposed filters).  Most are still applicable in drupal 8, with the .tpl.php file ending swapped out as .html.twig


You need to have the Geofield module installed instead. You can then add location information e.g Longitude/Latitude.


How to add item to cart programmatically, with attributes in Ubercart

Taking Chris's answer an putting it in Answer format for readability.

Figured it out, perhaps this will be of help for someone :)

$product_nid = 2;
$some_data = array('attributes' => array(
                   '1' => '1',
                  ),
             );
uc_cart_empty(uc_cart_get_id());
$data = serialize($some_data);
uc_cart_add_item($product_nid,
                 $qty = 1,
                 $data,
                 $cid = NULL,
                 $msg = TRUE,
                 $check_redirect = TRUE,
                 $rebuild = TRUE);


Finally, I was able to solve this issue adding the method permission to the RestResource plugin like so:

public function permissions() {
  return [];
}


How to add multiple taxonomy term to a single node in drupal 7?

Go to Term Reference Field settings of the content type and change 'Number of values' to  your required value.

For example if you want to allow 2 terms per node change the allowed number of values to '2' from select list. If you want to allow more than 10 or so change the option to 'Unlimited' so that you can insert multiple taxonomy terms to a node separated by 'comma' (,).

Here I've provided screenshot to allow unlimited values. Here 'SECONDTERM' is my    Term Reference of Autocomplete term widget field label name.


Print date and timestamp in views-view-field--blog--block-1--image.html.twig

I am assuming that the template is for a date field and you want to display the date field in the format that you specified above.

Here is the article that might help http://twig.sensiolabs.org/doc/filters/date.html

For PHP date formats you may refer to http://php.net/manual/en/datetime.formats.date.php

Similar question : https://stackoverflow.com/questions/8318914/how-to-render-a-datetime-object-in-a-twig-template


They are stored in the feeds_item table in the database. They are used by the feeds module to control updates of imported items.


What is the alternative to drupal_realpath()?

To get the HTTP path of a file, you need to use file_create_url($uri).

file_create_url('public://php_includes/functions.php');

This will output http://mysite.com/sites/files/php_includes/functions.php.

Regarding the fact that drupal_realpath() is deprecated, I think it's to warn developers to avoid relying on file system path and instead use wrappers.


How to change "Secure Login Module - Secure base url" without login?

It's in the variables table. Variable name is securelogin_base_ssl, value like s:4:"theurl";


How to include multiple Views in an already existing feature?

Feature module provides admin interface for each feature you create.

Just go to this page: admin>structure>feature
Find your feature
Edit it and check which Views to add.
Rebuild your custom feature module which your edited.
Open the code, delete old custom_feature module and add new custom_feature module which you just created.

You are done!


Since Drupal 8 uses Symfony's request stack which generates the base url, some things are not possible to do in the same manner as was possible in Drupal 7.
Instead create sites/default/drushrc.php and add
<?php

$options['uri'] = 'http://mysite.local';

and you should be fine.


Prevent comments containing html links from beeing validated

Why can't you go for Mollom

  Mollom may block a post outright if it is from a known spammer. If
  Mollom is unsure how to classify a post, it may require the completion
  of a CAPTCHA to accept the post. Posts that do not match a "spammy"
  text pattern and do not originate from known spammers are accepted
  without the need to complete a CAPTCHA. Essentially, Mollom acts as a
  proactive content moderator that is on the job 24 hours a day, 7 days
  a week.


Is there a simple way to alter core node/add/my_node_type to adding/my_node_type?

I didn't test this code, but if I'm not mistaken, it should be as simple as doing this in a custom module:

function YOUR_MODULE_NAME_menu_alter(&$items) {
  $items['adding/my-node-type'] = $items['node/add/my-node-type'];
  unset($items['node/add/my-node-type']);
}

Something similar could be done for the editing path.


User login block doesn't appear for authenticated user

The user login block will never appear for any user other than anonymous users, as users are already logged in, so it makes no sense to have a login block when they are already logged in.


How to change a custom field on form save

You create a custom module that will include hook_form_alter().   Something like this:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    global $user;

    if (in_array('admin', array_values($user->roles))) {
      //admin role is not a default role
      //do nothing
    }
    elseif (in_array('authenticated user', array(values($user->roles))) {
      //remove editable field and replace it with a label
      $form['article_field_rejected']['#access'] = FALSE;
      $form['article_field_rejected_label'] = array (
         '#type' => 'item',
         '#default_vale' =>  isset($field['article_field_rejected']['#value']) ? $field['article_field_rejected']['#value'] : '0',
    }
    else {
     // For everyone else disable field and do not display it
     $form['article_field_rejected']['#access'] = FALSE;
    }
}

If you don't replace the field with a label, then the use can still alter the value by editing the browser.


You haven't specified which Drupal version you are using, but check out Menu Subtree Permissions for D6.


Following up on Volker's comment, I created a new person with the name "award_name description" and assigned the proper award to the person just created.

In Views Accordion settings I checked the box "Add views row classes
Add the default row classes like views-row-1 to the output."

Style the views-row-1 class to make the description pretty.

I have the setting "Add striping (odd/even), first/last row classes", so i had to edit the CSS to swap even and odd so the description has a white background.

Hope this helps someone with a similar problem!


Receive the error PDOException: SQLSTATE[23000] when trying to update some content text

Looks like an error with the module

pinit

It's inserting a duplicate row for nid into it's database table.

It should probably use db_merge instead.

You may need to raise a bug report with the module maintainer.


Drupal 7 returning empty array because of the database connection

I resolved it. The problem is not in the database connection. I cleared the cache table in the database and it started working fine.

Earlier, I set the option 'Cache pages for anonymous users'. May be because of this, it didn't give the output.

Thanks for your answer.


Exposed filters in views with Ajax turned on doesn't generate url

Use Views Ajax history to accomplish what you are asking. There are a couple of bugs when using supporting modules such as Views Infinite Scroll, but for the most part this allows you to keep browser history as you add filters and change pages, allowing your user to use the forward and back buttons in their browser.


If memory serves me well I think the easiest way is to simply print the output in your page callback function, and not return anything:

function MYMODULE_popup_page_callback() {
  // Your theme variables
  $vars = array('foo' => 'bar');
  $output = theme('MYMODULE_popup_page', $vars);

  print $output;

  // If there's nothing more to be had from this page request you might as well end it (gracefully).
  drupal_exit();
}

The other, more involved way, would be to override the default delivery callback for your menu item. The default is drupal_deliver_html_page(); if you want to go down this route I'd recommend reading and understanding that function to see what you'll need to do in your own function.


Hook form alter to check date field is empty or not

The last one should be correct if the form has a field called field_start_date.

You fetch values from the form_state like this:

$form_state['values']['FIELD_NAME'];

To see which values are available in the form_state you can use the devel module to print the values from the form state using dpm($form_state['values']).

UPDATE: You can't really use drupal_set_message() to print arrays, you must use dpm, kint, print_r or other functions that allows you to debug an array.

You can use e.g dpm($form_state['values']['field_start_date']) to see where the values live.


Converting a form field to multiple submit buttons?

I would like to suggest is, use  hook_form_alter, create an ajax handler on value change on select list, disable ( remove) submit button.
/**
 * Implements hook_form_alter().
 */
function YOURMODULENAME_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'YOUR_FORM_ID') {
    $form['YOUR_FIELD_MACHINE_NAME']['#ajax'] = [
        'callback' => array('mycustomSubmit'),
        'wrapper' => 'vote-wrapper'
      ];

      $form['YOUR_FIELD_MACHINE_NAME']['#prefix'] = '
',
      $form['YOUR_FIELD_MACHINE_NAME']['#suffix'] = '
';
    // disable submit button
    $form['actions']['submit']['#disabled'] = TRUE;
 }
}

  /**
   * {@inheritdoc}
   */
  public function mycustomSubmit(array &$form, FormStateInterface $form_state) {
    // YOU CAN DO NODE CREATION HERE,
    \Drupal::messenger()->addMessage($this->t('YOUR SUCCESSFUL MESSAGE'), 'status', TRUE);
  }

and in twig template theme the select options instead of radio, theme them in a button like what you want. ( or even you can  style radio options as button with just CSS)
for reference: Customize Radio Button Appearance with CSS


How to add custom theme for Add a Product page

It depends what part of the page you want to theme, simple CSS, change the layout, or adjust the form.

To add CSS, you could attach your CSS file in hook_page_build for that path.

To change the page template, you could override the page.tpl.php file as page--node--add--product.tpl.php

You could also set a custom template in hook_preprocess_page by checking for the relevant path and setting theme_hook_suggestions to your template (e.g node/add/product and node/[nid]/edit)

Another option is using hook_custom_theme to specify a whole new theme for that specific path.

Lastly, you can theme the form itself using hook_form_alter and using either a template for the form, or adjusting the form elements there.


I found this answer for Theming forms on alter with Drupal 7 on Stack Overflow:

  Themes for Drupal 7 form elements need to use the new render array key instead of variables in the theme definition:

function mymodule_theme() {
  return array(
    'custom_radios' => array(
      'render element' => 'element',
    ),
  );
}

  Once you've made the change, clear Drupal's caches and your code should work (I've just tested the above and it works fine).


Link static HTML, Javascript and CSS3 in a Drupal Site

I think the best option for what your describing is to take a screen shot of the site and use that; as an image will not display the html/css/js. https://www.drupal.org/project/phantomjs_capture is the project I would use; this is a very odd request so in order to achieve this you'll have to do some custom coding.

If your looking to obfuscate the JavaScript by minification AdvAgg can help but it's not setup to fully obfuscate the JS as it will point to the source file by default (for GPL compliance). This could be changed; if you do decide to go down this route open up a request in the advagg issue queue and I'll add in a hidden option to allow this to happen.


I have selected third option of 'Download Range Options' and its working properly.


db_select subquery "In" condition causes PDOexception

The only problem with your query is that you're using index as a table alias...this is a MySQL reserved word and although my instinct is that PDO should escape this, perhaps it doesn't.

The following code (with the aliases renamed) runs without error:

$vocab = 2;

$subquery = db_select('taxonomy_term_data','ttd')
  ->fields('ttd',array('tid'));
$subquery
  ->join('taxonomy_term_hierarchy', 'th', 'ttd.tid=th.tid');
$subquery = $subquery
  ->condition('ttd.vid',$vocab)      // vid of vocab we want to show
  ->condition('th.parent',0);  // tid of parent (We want toplevel terms)

$toplvlcats = db_select('taxonomy_index','ti');
$toplvlcats
  ->join('taxonomy_term_data','ttd','ti.tid=ttd.tid');
$toplvlcats = $toplvlcats
  ->fields('ti',array('nid'))
  ->fields('ttd',array('name'))
  ->condition('ti.tid',$subquery,'IN') // Sift through toplevel terms
  ->orderBy('COUNT(nid)','ASC')           // For the one with the most posts
  ->range(0,4)
  ->execute();


adding data to an existing content type programmatically

Matt,

To create a node programmatically,

You firstly need to create a content type for same. This will make sure that Drupal architecture is followed to create a node.
Now you need to create a node from UI, and in hook_node_presave, make sure you print the node object - dprint_r($node); die; and see what is the Object architecture like.
Now you need too create the same object before saving it.
To, create the object, create $node = new stdClass();, define the node type $node->type = 'YOUR CONTENT TYPE NAME' and do a node_object_prepare($node), this will make sure that all the basic settings are added to the node object.
Post this, make sure you create the object, same as it was in node presave stage.
Just before calling node_save, call node_submit, which will prepare the node for submission.

Hope this helps !!!


In Views/Block view/Styles (gear icon) change Calendar day of week names to Abbreviated name.


Are you using Drupal 6, or Drupal 7? You should look into the Content Construction Kit module, which would easily allow you to add images to nodes and arrange them. You can set the number of allowed elements to "unlimited" for multiple images.  If you want to be able to place your node images on different parts of the node page, try the Panels module.

Update in answer to first question, below

Why yes; one of the great strengths of Drupal is its ability to let you just plop down some php anywhere in the page you need to put it (but please, don't put your php in the database, if you can help it!).  If all you wanted to do was display images from a folder at a given URL, rendered in your own code, all that you would need would be a menu with 'page callback' set.  If you want to modify a node, though, then you will need to learn about the scary render array.  When you find something in the page that you want to change, the easiest thing to do is to set the #markup element to the exact HTML content you want to display. If you do not want to replace an element, you can use #prefix or #suffix to put HTML before or after the given item.

If you make yourself a theme, you can add a preprocess hook to it (in template.php):

function MYTHEME_preprocess_node(&$variables, $hook) {
  if ($variables['node']->type == 'page') {
    $variables['content']['field_document_file']['#prefix'] = '
';
    $variables['content']['field_document_file']['#suffix'] = '
';
  }
}

This snippet, simplified from the above-quoted article on render arrays, adds a div around the CCK field called 'field_document_file'.  In your case, you'd probably just want to put some HTML into #suffix after the node body, which I believe is simply $variables['content']['field_document_file']['#suffix'].  To find out what's in a render array, install the devel module, and add a dpm($variables) to your preprocess function.  You're also likely to find the search krumo module to also be highly useful.

As far as actually getting the images onto the page, I trust that you can write your own code with file_scan_directory. Just remember to write secure code when outputting any data that was supplied by the user.

Anyway, that is what you would do; in general, just adding cck image fields and populating those with the images you currently have stored in folders might be easier.  drush entity might help out here. If you have a special need to keep your images in folders, then it's render arrays for you.

An easier option might be to just put your php code in a node-page.tpl.php. I rejected this as an option at first because I felt it would not give you enough flexibility to position your elements in the html output. However, with node-page.tpl.php, you could put your images before or after the node contents, and perhaps adjust the positioning to your satisfaction with css. This would be easier than fixing up the render array.


Is there a date / time format that only shows minutes if they are non-zero?

A bit of a cludge but if your output allows simple html, you can write a format that includes a span around the colon and minutes and use the minutes as a class.  Then hide the span if it's 00.  E.g.

M. d, Y - g<\s\p\a\n\ \c\l\a\s\s='\m\i\n-i'>:i<\s\p\a\n\>a

Then css of

.min-00 { display: none; }

I've done this with dates to produce over/under large date/small month displays. If it's coming from a view, you may need to check the allow html option on the field.


Devel Krumo outputting all variables in a list format and not in an expandable clickable list

If you are using bootstrap 3, you might encounter this problem. To fix this issue, add the following code to your template.php file.

function THE-THEME-NAME_status_messages($variables) {
  $display = $variables['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );
  foreach (drupal_get_messages($display) as $type => $messages) {
    $output .= "
\n";
    if (!empty($status_heading[$type])) {
      $output .= '
' . $status_heading[$type] . "
\n";
    }
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
        $output .= '
' . $message . "
\n";
      }
      $output .= "
\n";
    }
    else {
      $output .= reset($messages);
    }
    $output .= "
\n";
  }
  return $output;
}


Render custom block using block.html.twig template

BlockContent is the only entity in Drupal not having a template of its own. So you have to wrap it in a template yourself:

$block = \Drupal\block_content\Entity\BlockContent::load($bid);
if ($block) {
  $content = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
  $build = [
    '#theme' => 'block',
    '#attributes' => [],
    '#configuration' => ['label' => 'My Block', 'label_display' => 'visible'],
    '#base_plugin_id' => 'block_content',
    '#plugin_id' => 'block_content:' . $block->uuid(),
    '#derivative_plugin_id' => $block->uuid(),
    '#id' => $block->id(),
    'content' => $content,
  ];
  return $build;
}


Drupal 8 webform 8.x-5.8 - how to show the previous step value in next step?

Use

HOOK_form_alter(array $form,FormStateInterface $form_state, $form_id)

check if $form_id equals your specific form (form's machine name) and validate if current page is page where you want to display data ('step_5' is wizard's page machine_name).

if ($form['progress']['#current_page'] === 'step_5')

get values from $form_state

$form_state->getValue('select_your_data_type')

and you can set form elements via

$form['elements']['page_5']['field_i_want_to_set_in_page_5']

or via

$form_state->set('field_i_want_to_set_in_page_5', $my_value);

or course do not forget to print field_i_want_to_set_in_page_5 somewhere on page 5.


You should be able to define something like this:

'visible' => array(
  array(
    ':input[name="ELEMENTNAME"]' => array(
      array("value" => 'VALUE_1'),
      array("value" => 'VALUE_2'),
    ),
  ),
),

See this question  for more details


Allowing anonymous users to contact node authors

I'm pretty sure this can be done by combining the core Contact module with the Contact Storage module.
Steps to implement

Enable the Contact module and give anonymous the permission Use users' personal contact forms.
Enable the Contact Storage module and create a view showing Contact message. Configure a contextual filter with the user ID so that only messages to the logged-in user are displayed.


As this Drupal core issue shows, this error has made an appearance from time to time. From a reading of the thread, it looks like it is often related to a content type that is referencing a missing taxonomy vocabulary. I recommend checking your vocabularies against your content types to make sure everything is correct and consistent.


How to add constraints to custom data arrays?

You cannot validate generic data against a list of constraints you create.
Constraints are attached to specific typed data objects, entity fields, or entities. You can only validate them against the constraints they have, and you don't need to get first the list of the constraints that apply.
If $entity contains an entity, you can use the following code to check if it validates against its constraints.
$violations = $entity->validate();
if ($violations) {
  // The entity didn't pass validation from constraints.
  // For each validation $validation->getMessage() returns the
  // error message. $violation->getPropertyPath() returns the property
  // path for the property that failed validation, for example
  // field_text.0.value, if the validation failed for the value property of
  // field_text.
}

To validate only a single entity field, for example field_text in $entity, instead of $entity->validate(), which would validate the entity and all its entity fields, the method to call is $entity->field_text->validate().


Install the Field default token module and then edit the entityforms type and save again with the desired tokens selected, and it should work.


I looked at some other modules controllers and saw that in the controller they used

$result = db_query
$output = $result->fetchAll();

Before pushing the code to the return array. I tried it and it worked for me like it should. Problem solved.


Is there a product.tpl.php for ALL product types in Drupal Commerce?

You could do the following in your theme processing...

function YOURTHEME_process_node(&$vars) {

    //dsm($vars);
    //dsm($vars['theme_hook_suggestions']);

    // If some node type then...
    if ($vars['node']->type) {
                // add a template suggestion
        $vars['theme_hook_suggestions'][] = 'node__product';

    }

}

Then you add a template file 'node--product.tpl.php'.


Changing Allowed HTML tags: @tags for help text input field

There isn't an easy way to do it really, the list of allowed tags is hard coded into the _field_filter_xss_allowed_tags() function.

This is in turn called by field_filter_xss(), not when the data is saved to the database but rather when it's displayed in field_default_form().

Fortunately there is a way but it'll take a small custom module to do it. You're basically looking to implement a form alter hook for the field's widget form and set the element's description to use filter_xss() with a more permissive set of tags.

Something along these lines:

// Implement hook_field_widget_form_alter()
function MYMODULE_field_widget_form_alter(&$element, &$form_state, &$context) {
  // If some condition is matched based on the element provided...
  if (isset($element[0]) && $element[0]['#field_name'] == 'field_test') {
    // Alter the description using your more permissive set of tags
    $element[0]['#description'] = filter_xss($context['instance']['description'], _MYMODULE_field_filter_xss_allowed_tags());
  }
}

// Provide a more permissive set of tags to be used with filter_xss()
function _MYMODULE_field_filter_xss_allowed_tags() {
  // Merge the new set of allowed tags with the less permissive defaults
  $new_tags = array('table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td');
  return array_merge(_field_filter_xss_allowed_tags(), $new_tags);
}

That's based on the premise that you only want to allow the new tags for an element called field_test, obviously if you want to do the same for other fields you'll need to change it to match a different condition. I advise using the excellent dpm() function included in the Devel module to inspect object in your form alter function.

I've just tested the above and it works (I now have a table where my file field description would normally be), it feels a bit like a hack even though it technically sticks to the rules but hopefully it'll get you on the way.


How do I include the full body field in the RSS feed for a taxonomy term?

Drupal 6:

The easiest way is to:

Change the setting in
/admin/content/rss-publishing

Or:

Install views
Enable taxonomy_term view
Edit the 2 Feeds

Click on the gear right of Row Style
Change to full text


you will have to add a new display type in your views "PAGE" and give it a path so you can goto that page directly.


Removing divs added by render and node.tpl.php

The div ids and classes you see inside $page['content'] comes from region.tpl.php > block.tpl.php > node.tpl.php
Drupal content passes through these template files, each step adds some divs.

Step One

region.tpl.php file contains  the code as follows

       <?php if ($content): ?>
  <div class="<?php print $classes; ?>">
    <?php print $content; ?>

<?php endif; ?>

now if you make changes in this file it will effect all the regions of your page. If you want to control only the content area, create a new file name it region--content.tpl.php in that file paste only

<?php if ($content): ?>

    <?php print $content; ?>

<?php endif; ?>

This will get rid of div created for only content region.

Step Two

Make a copy (if we make changes in block.tpl.php all the blocks will be effected) of block.tpl.php and name it block--content.tpl.php and remove or change the divs. Without the divs the file will contain the following code to output content.

<?php print render($title_prefix); ?>
    <?php if ($block->subject): ?>
      <h2 class="block-title"<?php print $title_attributes; ?>><?php print $block->subject ?>

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

This will get rid of div created by bock.tpl.php

Step Three

Now edit the node.tpl.php file to remove or change the divs. Without the divs the file will contain the following code to output content.

          >">

    <?php print $user_picture; ?>

    <?php if ($display_submitted): ?>
      <?php print $date; ?> — <?php print $name; ?>
    <?php endif; ?>

        <?php
          // We hide the comments and links now so that we can render them later.
        hide($content['comments']);
        hide($content['links']);
        print render($content);
       ?>

    <?php if (!empty($content['links']['terms'])): ?>
      <?php print render($content['links']['terms']); ?>
    <?php endif;?>

    <?php if (!empty($content['links'])): ?>
        <?php print render($content['links']); ?>
      <?php endif; ?>

<?php print render($content['comments']); ?>

This will get rid of all div and classes. Now you can wrap the content with your own divs.  Please let me know if it works for you.


Password Gets Reset when executing user_save

Be sure to

unset($edit['pass']);

if you don't want to edit password. Generally creating $edit from $existing shouldn't be needed. You do not need to re-save all fields, you only put into $edit what you know you want to change. You should, usually, be able to start with empty array, without seeding it first.


Creating a form that only show form fields for editing the node title, body, and any fields created using the field API

I get you want to show a form where the users can enter the values for the fields implemented using the field API, the node body, and the title; other form fields should not be shown.

Using the following code, you can achieve what you want.

function mymodule_node_form($form, $form_state, $node) {
  global $user;

  if (!isset($form_state['node'])) {
    if (!isset($node->title)) {
      $node->title = NULL;
    }
    node_object_prepare($node);
    $form_state['node'] = $node;
  }
  else {
    $node = $form_state['node'];
  }

  $form['#node_edit_form'] = TRUE;

  $form['#attributes']['class'][] = 'node-form';
  if (!empty($node->type)) {
    $form['#attributes']['class'][] = 'node-' . $node->type . '-form';
  }

  foreach (array('nid', 'vid', 'uid', 'created', 'type', 'language') as $key) {
    $form[$key] = array(
      '#type' => 'value',
      '#value' => isset($node->$key) ? $node->$key : NULL,
    );
  }

  $form['changed'] = array(
    '#type' => 'hidden',
    '#default_value' => isset($node->changed) ? $node->changed : NULL,
  );

  $function = node_type_get_base($node) . '_form';
  if (function_exists($function) && ($extra = $function($node, $form_state))) {
    $form = array_merge_recursive($form, $extra);
  }
  if (isset($form['title']) && !isset($form['title']['#weight'])) {
    $form['title']['#weight'] = -5;
  }

  $form['#node'] = $node;

  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
    '#value' => t('Save'),
    '#weight' => 5,
    '#submit' => array('node_form_submit'),
  );
  if (!empty($node->nid) && node_access('delete', $node)) {
    $form['actions']['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete'),
      '#weight' => 15,
      '#submit' => array('node_form_delete_submit'),
    );
  }

  // Add the validation handlers.

  field_attach_form('node', $node, $form, $form_state, entity_language('node', $node));
  return $form;
}

This code is taken from node_form(); it is a ripped off version that include only what necessary to allow to enter the title, the body content, and the values for any field implemented using the field API.
As you see, the code still need to define the form validation handler, and the form submission handler. You use the code of node_form_validate() as guideline for your
validation handler.

The form builder can be used for a menu item as the following one.

function mymodule_menu() {
  $items['mymodule/%node/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_node_form', 1),
    'access arguments' => array('the permission users should have to see this menu item'),
  );

  return $items;
}


There are a number of permissions that could be affecting this.

First off, node permissions.  The most important one here is 'access content,' so make sure anonymous users can do that. After that, they can be set up so different users in different roles can create, delete and/or edit nodes.

Given that they aren't trying to do any of this, I doubt it's related to these node permissions, so let's go drill down a granularity level and look at permissions on fields in the nodes themselves.  Here, permissions can be set on edit and view.  Given they aren't trying to edit a node, just look at it, I'd look at the view permissions.

Assuming 'admin' is uid 1, s/he can do anything, so look for fields that aren't viewable by the more casual user/role.  Somewhere in there as you surmised above is the field that this module needs to show itself.  (Oh, also, if you are using imagecache, make sure its permissions are set up as well)


The Global Redirect module will fix this right out of the box.

Once enabled, it'll make sure there is only one canonical path available: your custom one. So all mentions of locations/los-angeles created by Drupal will be replaced with california/los-angeles, so that if you try to access locations/los-angeles it'll redirect to california/los-angeles.


Drupal form elements in html table, label (title) rendering

My not nice solution is

function drupal_render_label($field){
    $result= "
";
    $result.= "".$field['#title'];
    if ($field['#required']==true){
       $result.= "*";
    }
    $result.="";
    $result.="
";
    return $result;
}

and then:

  $content.="";
  $content.=drupal_render_label($form['carmodel']);
  $content.="	";

Anyone have sth better?


Problem solved!

In Format/Settings set Grouping Field 1 to Parent.


Attach a Webform to user registration form

It sounds like you want the Webform Registration module. It lets any webform create users upon submission. It also lets you customize the registration process by selecting which webform elements are associated with the newly created user's name, password, & email.


Internet Explorer 11 Overlay does not close

I fixed it yay! It was a problem with jquery update. I updated the module to the alpha3 release which adds support for jquery version 1.11 and it works fine now.


Services Module - 500 Internal Server Error When Accessing REST URL

The problem turned out to be the PHP version on the server.  The Rest Server had a line of code that requires PHP 5.3.

There is an issue at https://drupal.org/node/2003396 and a patch at https://drupal.org/files/ServicesRESTServerFactory.inc_.patch

Installing the patch solved the problem without the need to upgrade the php version on the server


Are you looking for Field Collection?
You can create collection with Node Reference field and Date field. Then Field Collection Table will help you with outputting.
This exactly works with Entity API.


How to provide upload function for users

You have a few options:

Use a contributed module.  Take a look at this link for a list of modules: File Uploading and Managing. A few that are definitely worth taking a look at are: FileDepot, WebFM, and ELfinder
Create a content type where you can upload files (using the core image module if D7 or if D6, the Image or ImageField modules)
Create a custom module to your exact specifications.  This is definitely the most customizable option, but involves more work and a familiarity with the API. To get started creating a custom module, take a look at the Module developer's guide, the Forms API Reference, and the Form API Quickstart Guide


Custom node access, need to rebuild permissions for each content item created

It seems like your problem matches the following:

  This function is called when a node is saved, and can also be called by modules if something other than a node save causes node access permissions to change.

This is an excerpt from the node_access_acquire_grants documentation.
I believe a way to go about your problem would be to call this function, inside your form_submit handler (guessing you have one).

So, on a conceptual level, as soon as the anonymous user enters the code, the node access permissions for that specific page changes and you should update them (writing them to the database) through a call to node_access_acquire_grants

Good luck, let us know how this goes!


Condition in variation product template is not triggered correctly (ajax caching ?)

If you have other input data(url, query params, timestamp, cookie, etc) than $variables in your HOOK_preprocess you have to update your cache rules otherwise first time you get trough that hook will get cached for the rest of iterations of same $variables input.
In your case I suggest using cache context or cache tags where they change based on POST and GET variables.
https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays


xpath XML parser is not parsing anything, neither does give any debug info

Solved. Module had some odd bug. Cloning earlier working importer and changing it identical to above worked.


Media library duplicating results view in ckeditor

This is a shot in the dark, but are you running jQuery Update module? If not, you should give it a try and set the admin area to use jQuery 1.7. Drupal 7 core shipped with jQuery 1.4, and some modules evolved to needing a newer version of jQuery. jQuery Update will solve that for you.

https://www.drupal.org/project/jquery_update


Have you ever tried Field Permission. I think it'll help to solve your requirements. Check the video tutorial to use that module Drupal 7 Field Permissions Module


How to make a parent - child taxonomy list

Yes above answer works, but parent terms are showed at top of view, so it's nice to remove them. I use Views Hacks module , and only check Selective Exposed Filters.
For filter select Taxonomy term: Parent (selective) and choose is not one of all
You can view my view at http://www.attorney-directory.net/practice-areas


Drupal 7 Search results have no theme or format (no HTML)

I don't know if this will help anyone; but, just in case, here is the solution to my problem.

One of my content types (the one causing the issue) is only viewable in the public site via ajax.  As such, I had this code in my function *mytheme_node_view_alter(&$build)*

//show only output for popup
if($build['#node']->type=="blue_pop_up"){
    echo $build['#node']->body["und"][0]["safe_value"];
    die();
}

This was breaking my search results page when it found content of this type. I simply added this to the code:

//show only output for popup
    if($build['#node']->type=="blue_pop_up")
    {
        if($build["body"]["#view_mode"] != "search_result")
        {
            echo $build['#node']->body["und"][0]["safe_value"];
            die();
        }
    }


I get the impression you want to create pages out of components, so rather look at Panels (and Panels Ajax Tabs).

In order to use panels properly you have to learn how to use Page manager also as Panels integrates with it. The best online tutorials on that subject are from Johan Falk at Node One, Learn Page Manager! series. Tutorial 4 - 7 of that series deals specifically with Panels, but start at the beginning and work your way through it. You will also learn a lot about context which is an essential concept to master as a Drupal site builder.


How to make nice content manager approval page?

I guess Views Bulk Operations (VBO) may help you here. Here is a quote about it (from the module's project page):

  ... This module augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.


You can create the node template for your content type. You can review the template suggestions link for reference.

You can add below code in your template file to generate a link for the comments.

print render($content['links']['comment']);

Kindly see that you need to uncheck 'Show reply form on the same page as comments ' checkbox in the comment settings for your content type.


Well, just off the bat I haven't seen anyone use single quotes on the human-readable name. For instance, I'd change it to:

regions[alert] = Sitewide Alert

You might have a PHP if statement in your page.tpl.php somehow affecting your content region. I'd double-check the template file and see how it matches up with the default Bartik page.tpl.php


Submit form load results instead of messages

The example of @Ajay was not working for me.
This one do. Hope this help.

public function buildForm(array $form, FormStateInterface $form_state) {

    // Your $form fields here ...

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    );

    // Render this field bellow the submit button and above return $form.
    if (!empty($formValues = $form_state->getValues())){

      $header = ["Key","Value"];

      $output = [];
      foreach ($formValues as $key => $value) {
        if ($key=='submit'){
          break;
        }
        $output[$key]['key'] = $key;
        $output[$key]['value'] = $value;
      }

      $form['mytable'] = [
        '#type' => 'table',
        '#header' => $header,
        '#rows' => $output,
        '#empty' => t('No Data'),
      ];
    }

    return $form;
}

public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRebuild();
}

Soon I'll write a post about other ways to render form's data in a controller or even with a Private Temp Storage


how to manually add a node in drupal 7 in the database

Because you are trying to understand Drupal database concept, you are checking every insert you made in the Drupal admin section, and by doing so Drupal is caching your data.

So you are not missing anything. You only need to clear Drupal cache, try to truncate each cache table one by one.


You could also try Page Preview, which shows a simulated full-page preview of a node:

  This module re-implements the Preview area of the node edit form as an
  IFRAME that renders and displays the full page view of your edited
  content as the anonymous user would see it, including elements such as
  blocks that display as a reaction to the page context.


That is just your pretty URL.  Your actual url is something like this node/52.

So in your contextual filters, choose provide default argument and then select the content id from the URL.  Views will pull in the 52 number for your referenced entity and that will filter your block accordingly.

UPDATE
Since you are manually creating your URLs, and idea here would be to grab the first and second element from your path.  I do not recommend this.  I would recommend you adding another field to reference the artist on the news basic page so you can use that value in your contextual filter.  Anyway here is what you could do.

In the contextual filter, when providing a default value, use the PHP filter and add something like this to return the value of the NID of the artist.

$path = drupal_get_path_alias($_GET[‘q’]);
$path = explode(‘/’, $path);
// This path should be something like artists/picasso
// The idea here would be to get the artists node path
// and then retrieve the node id from that.
$node_artist_path = drupal_get_normal_path($path[0].'/'.$path[1]);
// ^ should return something like node/33
$nid = arg(1,$node_artist_path);
return $nid;

This will return the value of nid from the artists main path.  AGAIN I do not recommend this as its very dependent on path aliases.

Also I did not test any of this code, I may have some functions wrong and if I do let me know and I will update it, this is all from memory.


You'll want to use taxonomy_save_term. The array you pass in to taxonomy_save_term should look like this.

$term = array(
 'name' => 'Taxonomy Term 1',
 'vid' => 1, // The VID of the vocabulary this term should be saved under
 'description' => 'A description of this term', // Not required
 'weight' => 5, // Not required
);
taxonomy_save_term($term);


How to save each array values in next line?

You should pass paths as a string instead of array:

$test = "abc/*\nxyz/*\nijk/*\n";
variable_set('boost_testing', $test);

Remember to use double quotes for the $test string.


Drupal 8 - Use the current node ID (on node edit form) to filter an entity-reference view as a contextual filter

This might not be THE answer.
But for my specific need, and because we already are late on this project.
I found a "quick-fix" solution.. waiting for a more drupalistic one.

Assuming that this entity-reference-1 view display is always called from a node/:nid/edit page, I should always have a HTTP_REFERER on each request to the view (I guess ^^). Well, I check that for insurance.

Inside a hook_views_pre_view hook, I pass the node-id from the HTTP_REFERER to the view, like this :

<?php

use \Drupal\node\Entity\Node;

/**
 * Implements hook_views_pre_view()
 *
 * Alter the contextual filters for my view :
 *
 * When the HTTP_REFERER is a node/:nid/edit pattern and the view-display is an entity-reference
 *  then I fetch the node ID from the URL, I load the node to check the node type
 *  and I pass this nid to the view as an arg
 */
function MYMODULE_program_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'view_program_related_contents' && $display_id == 'entity_reference_1') {
    if (isset($_SERVER['HTTP_REFERER'])) {
      $referer_url = parse_url($_SERVER['HTTP_REFERER']);
      $path = htmlspecialchars($referer_url['path']);
      if (preg_match('/node\/(\d+)\/edit/', $path, $matches)) {
        $node = Node::load($matches[1]);
        if ($node instanceof Node) {
          if ($node->getType() == 'program') {
            $args[] = $node->id();
          }
        }
      }
    }
  }
}

Again, I think I'm missing something in my entity-reference field definition, or my view configuration.. but I don't have enough time to spend on this.

I hope this helps..


Allow a user to manage his/her own users and be able to assign roles

Have a look at the Group module (commonly perceived as an alternative for Organic Groups).

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.

The way you described in your question how you imagine using the (great!) Flag module, translates more or less to "Is user X yes or no member of Group G?" combined with "What group roles does this user have". However, after you will understand / realize all the things you can do with the Group module (with zero custom code ...), you'll probably also understand that trying to do something similar with the Flag module, is going to take a lot of flags, and related Rules logic.

More info

Some more questions you may want to look at for more details:

How to configure access to courses for teachers and students?, which contains a sample configuration.
What are the various roles supported by the Group module?, which explains the various types of roles that can be used.
How to bulk assign existing content to a group created with the Group module?, a typical issue when adding this module to an existing site.
What are the features of the Group module versus Organic Group module?

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Calling a module function from jQuery and Ajax

To answer to The second block of JS code is a test I am trying to do to call the ajax_username function of ajax_example.module. you wrote in your comment, what you can use in JavaScript code like $.ajax({url: 'ajax_username'}) as url is a route exposed in the hook_menu() implementation of a module, or the path of a PHP file. It isn't the name of a PHP function implemented from a module, nor the name of a file containing Javascript code (without the .js extension).

As concrete example of what Drupal core modules do, see the content of the statistics.js file.

(function ($) {
  $(document).ready(function() {
    $.ajax({
      type: "POST",
      cache: false,
      url: Drupal.settings.statistics.url,
      data: Drupal.settings.statistics.data
    });
  });
})(jQuery);

What $.ajax() gets as url is Drupal.settings.statistics.url, set from statistics_node_view() with the following code.

$settings = array('data' => array('nid' => $node->nid), 'url' => url(drupal_get_path('module', 'statistics') . '/statistics.php'));

In the test site I am using, the output of url(drupal_get_path('module', 'statistics') . '/statistics.php') is /modules/statistics/statistics.php.

So, if you want to call the callback associated to your ajax_username menu, you need to use $.ajax({url: '/ajax_username'}) or $.ajax({url: '/index.php?q=ajax_username'}), but in both the cases, the module must be installed and enabled.

If you don't want to enable a module for that, you cannot use hook_menu(), but you could create a PHP file containing the code to use, in the same way the Statistics module does with its statistics.php file.
Be warned: Use this only if you know exactly what you are doing, as using the wrong code could be a security risk for your site and its data.

I would rather use hook_menu().


how to create view that display just 2 level of taxonomy vocabulary

It's simple. In fact, there is no need to add any relationship in the Views. Just create the taxonomy term view and add a filter criteria of Taxonomy term: Parent term. (see screenshot)
Then set the value to be equal to ''. This will fetch you all the parent terms as they don't have any parent! ('')


It really depends on your server and Drupal sites setup.

opcache.use_cwd=0 can ONLY be used if you can ensure that there is no duplicate filenames in the PHP files that the server PHP engine may run.

Note that PHP files are not only those with .php extension, but any of them that begin with the php symbol, like .module, .inc, .install, .tpl.php and so on (whatever extension could be used really).

There are a lot of Drupal setups where these duplicate filenames exists, so opcache.use_cwd=0 must not be used, like:

Overriden core tpl files from your custom theme or sub-theme.
Multisite configurations, or multiple drupal installations running in the same PHP engine.

Note that in a single PHP engine, OpCache (if active) is shared between ALL the PHP files that are running on it, so name collisions will happen if any filename is duplicated, if the subdirectory info is not appended.


You can continue easyResponsiveTabs.js as normal JS and add your function call. Also you can call this function almost anywhere (like tpl.php file), even in the block/node (where you are using this script for conversion) wrapped in the <script> tag like:

<script>
$('#demoTab').easyResponsiveTabs();
</script>

I would go with drupal_add_js in template.php file of your theme.

Update

Using drupal_add_js you can do it like this:

drupal_add_js('jQuery("#demoTab").easyResponsiveTabs();', 'inline');


Index View donot show 'Contains' operator for (exposed) filter

I used hook_search_api_views_query_alter from search_api_views.api.php.

function MYMODULE_search_api_views_query_alter(&$view, &$query) {
  // Altering the title filter to operator LIKE which is not available in the
  // views itself.
  if ($view->name = '[VIEWNAME]') {
    if (!empty($query->where[1]['conditions'][0][1])) {
      $query->where[1]['conditions'][0][1] = '%' . $query->where[1]['conditions'][0][1] . '%';
      $query->where[1]['conditions'][0][2] = 'LIKE';
    }
  }
}


Help getting the values from user profile fields from currently logged in user

You're missing a $ in your second line.. Should be $user->

I always use the below.

global $user;
$user = user_load($user->uid)

And then get the field like your last line. If someone else could confirm if that is a waste and there's a better way to load the field, that'd be great.


Arguably the simplest (and least Drupal'y) way:

In html.tpl.php:

<head>
<!--[if lt IE 8]>
<link rel="stylesheet" href="<?php print base_path() . path_to_theme(); ?>/css/ie7.css" type="text/css" media="all" />
<![endif]-->
</head>

Clear your theme cache if adding the template to your theme for the first time.
Install the module, Conditional Stylesheets, which allows you to add conditional stylesheets to a theme's .info file.
Add 37 lines of code to template.php.

New to StackExchange, hope I did the right thing here. Thanks, @jdu.


how to use a view to node field based on url

I am assuming, you have a node of type A, that refers to a node of type B through a node referance field "field_noderef" attached to node A. You want to display the details of node A when you visit node B.

Create a block type view. Filter as content type = A
Create a contextual filter "field_noderef", set a default value of "get NID from URL".
Display the block in node page of content type B *this part is important.


Display additional fields from included content with Entity Reference field

You can achieve this by setting a view mode (recommended: Teaser) in the node display for the entity reference field at /admin/structure/types/manage/[CONTENT_TYPE]/display, and then adding the price and picture fields to the Teaser display of the referenced entity.

If the referenced entity is also a node then it would have a similar path of /admin/structure/types/manage/[OTHER_CONTENT_TYPE]/display/teaser. The path would be different if it is not a node, but should be easily found for most custom entities through the UI under the commonly named entity page 'Manage Displays'. Once there view modes can be selected at the top of the page for editing them.


"b.handleError is not a function" on image remove/upload

You can update the jquery.form.js as found in this comment:

https://drupal.org/comment/7520175#comment-7520175

I tried on my system which also makes use of a newer version of jQuery and it works like a charm.


If by 'programmatically' you mean using PHP, then there seem to be two good options.

Create a template file, include the fancybox library if not already loaded, load the file path/names from your image directory into an array, tweak the array as needed, and call fancybox with the paths in your array.
Create a custom module that does essentially the same thing, but here you can also add an admin view to manage the images, set custom permissions, etc.


I got it!!!

Here's a simple 100% functioning exmple:

$form['delete'] = array(
    '#type' => 'submit',
    '#value' => t('Delete'),
    '#attributes' => array('onclick' => 'if(!confirm("Really Delete?")){return false;}'),
);

I hope this helps.

Happy coding :)


I suggest you to make use of the following hook:

function YOURCUSTOMMODULENAME_views_post_execute(&$view){

    switch ($view->name){

 case "YOURVIEWMACHINENAME";

    // Get the result of the view in a array
    $data = $view->result;

    // your custom code to add / remove instances after the view was executed

    // Set the result of the custom code back into the view
    $view->result = $data;
    break;

  }
}

Your custom code would be something like
If there are less then 5 elements and more then 1 elements in the data array add new elements to the data array coming from another view.

To execute a view in code u can use something like this:

  $reflang = views_get_view("NAMOFYOURMACHINENAMEVIEW");
  $reflang->set_display("NAMEOFYOURDISPLAY");
  $reflang->set_arguments(ARGUMENTSFORTHEVIEW);
  $reflang->pre_execute();
  $reflang->execute();

  foreach ($reflang->result as $row => $rowinfo) {
    // add this to the data array
  }

Hopefully this helps you to solve the problem.


How to print all Drupal commerce order variables available inside the template?

Try using dpm($order) for this.  This will give you most of what you need including the order author's uid:

$order->uid


Your levels are a bit confusing, I'm guessing it's to do with your project structure and doesn't provide relevant information about the reference hierarchy, so I'll just rely on the information you provided about which entity references which.

list all Child nodes with a ref to Section but no Parent(ER)

Even though you already solved this the solution that first comes to my mind is to list all Child pages where the ER field to Section isn't empty, and the ER field towards Parent(ER) is empty. No need for special NONE nodes.

You can do this by adding a Filter for each of those ER Fields and setting the Operator to Is empty (NULL) and Is not empty (NOT NULL) respectively.

Remove the current node from the list

Add a Contextual filter ID from the Content Category and configure it with these options:
    When the filter value is NOT available
    Provide default value
    Content ID from URL
    More
    Exlude

List siblings relating to same node through ER

To list siblings you first need one Relationship to get to the parent of the ER relationship (in your case Section), then another Relationship in reverse direction that is using the first one to find all other children of the parent. Then configure a Contextual filter to use the second Relationship, that is the one that is identifying siblings.

Add a Relationship Content referenced from field_section (or however it's called in your particular case), you can require it, this introduces the Section into the Views.
Add another Relationship Content using field_section, set it to use the Relationship from the previous step, you can require it. This is the reverse direction, pointing to all children that are pointing to this parent (Section).
Add a Contextual Filter ID from Content Category and set it to use the second relationship (field_section) and configure:
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria
Child
If this is a Block Display place it on Child nodes and it will show other children that relate to the same Section.

To check the Contextual filter with Views Preview, enter the NID of the Child node you want to simulate, and enter it for each Contextual filter.

If you have both the contextual filter that identifies siblings and the one that excludes the current node from the list (and the Child NID is 24) enter 24/24.

If you want to see all the results, unaffected by Contextual filters enter all/all.


Finding out what file was called immediately before error

If you are tracking down a weird error, editing core is perfectly acceptable.

Make sure everything is in your RCS.
Edit includes/menu.inc
Place a print_r(debug_backtrace()) near line 635, preferable at the top of _menu_check_access().  Alse print_r() the arguments.
Trigger the problem.
Figure out what happened.
Revert the site to the checked in RCS version.

My guess is you are getting weird path, and the argument is wonky for your access check.  In other words, you are trying to access check something that should really 404.


Is it possible to pass dynamic values in tokens in Drupal 7?

Might have worked myself into the solution via trial-and-error.

function hook_tokens( $type, $tokens, array $data = array(), array $options = array() ) {

    // Returnable markup...
    $replacements = array();

    // Handle Tokens...
    if( $type == 'modal' ) :
        foreach( $tokens as $name => $original ) :

            $name_parts = explode( ':', $name );
            switch( $name_parts[ 0 ] ) {

                case 'view':

                    // Handle modal:view tokens...
                    if( !empty( $name_parts[ 1 ] ) && !empty( $name_parts[ 2 ] ) ) :
                        $value =
                        ''.
                            ''.trim( trim( $name_parts[ 2 ], '"' ), "'" ).''.
                        '';
                        $replacements[ $original ] = $value;
                    endif;

                    break;

            }

        endforeach;
    endif;

    return $replacements;

}

There's a lot of fail-safes missing from this code, but I just want to make sure this falls under best practice and that I'm not doing anything that would be considered taboo by community standards.


How to use two different image styles on teaser?

You can use Entity View Modes

It will give you the chance to set up a new view mode and change it from Manage Display page.
You can create 2 view modes, one for Sticky e one for Recipes of the day.
From views page, open the sticky display, click on "Show -> Content > YOUR_VIEW_MODE" and repeat it for the Recipes of the day display/view.

In the manage display page you can set up the image style for the View Mode.


How do I programmatically create an entity with its fields?

Here's some code that creates a product programmatically, including fields and properties.

/**
 * Create a product programmatically.
 *
 * This is stolen shamelessly from commerce_bpc. However, I'm not comfortable
 * with the field saving using form api. Seems quite odd.
 *
 * @param $product_type
 *   (string) The name of the product type for which products should be created.
 * @param $values
 *   Keyed array with
 *   - 'price' => actual amount owed on this installment; decimal text like '1.50'
 *   - 'amount_paid' => price amount already paid as a decimal text like '1.50';
 *   - 'original_order' => order id of the original order
 *   - 'original_line_item' => line item id of original line item
 *   - 'original_product => product id of the original product from which the
 *     new product is being created.
 * @param $extras
 *   An array for the values of  'extra fields' defined for the product type
 *   entity, or patterns for these. Recognized keys are:
 *   - status
 *   - uid
 *   - sku
 *   - title
 *   Note that the values do NOT come in the form of complex arrays (as they
 *   are not translatable, and can only have single values).
 * @return
 *   The ID of the created product.
 */
function commerce_installments_create_product($product_type, $values, $extras) {
  $form_state = array();
  $form_state['values'] = $values;
  $form = array();
  $form['#parents'] = array();

  // Generate a new product object
  $new_product = commerce_product_new($product_type);

  $new_product->status = $extras['status'];
  $new_product->uid = $extras['uid'];

  $new_product->sku = $extras['sku'];
  $new_product->title = $extras['title'];
  $new_product->created = $new_product->changed = time();

  // field_original_order[und][0][target_id]
  $order = array(LANGUAGE_NONE => array(0 => array('target_id' => $values['original_order'])));
  $form_state['values']['field_original_order'] = $order;

  // field_original_line_item[und][0][target_id]
  $line_item = array(LANGUAGE_NONE => array(0 => array('target_id' => $values['original_line_item'])));
  $form_state['values']['field_original_line_item'] = $line_item;

  $product = array(LANGUAGE_NONE => array(0 => array('target_id' => $values['original_product'])));
  $form_state['values']['field_original_product'] = $product;

  //commerce_price[und][0][amount]
  $price = array(LANGUAGE_NONE => array(0 => array(
    'amount' => $values['price'],
    'currency_code' => commerce_default_currency(),
  )));
  $form_state['values']['commerce_price'] = $price;

  // field_due_date[und][0][value][date]
  $due_date = array(LANGUAGE_NONE => array(0 => array('date' => $values['due_date'])));
  $form_state['values']['field_due_date'] = $due_date;

  // Notify field widgets to save their field data
  field_attach_submit('commerce_product', $new_product, $form, $form_state);

  commerce_product_save($new_product);
  return $new_product->product_id;
}


Are there alternatives for striptags filter?

I am vehemently against things like render-array|render|striptags etc. It feels very unnatural and un-Drupal. What you should do is create a field template that has no markup.

For example, either in field.html.twig which would affect all fields, or in field--field-name.html.twig or more specific variants, you can do this:

{#
/**
* @file
* Theme override to remove all field markup.
*/
#}

{% spaceless %}
{% for item in items %}
  {{ item.content }}
{% endfor %}
{% endspaceless %}

This will always render that field with no markup.


Can I remove Zen Default Regions if Im not using them

You cannot remove regions that have blocks in them - at least not without consequences. If you will do so, blocks will disappear and there is a chance for Drupal and PHP errors. To get rid of unneeded regions, you need to proceed in that order:

Remove all blocks from them
Remove them from .tpl files, to be sure nothing will try to render region that does not exist anymore
Now you can delete them from .info file


Edit weight of block without using drag and drop

you can do it by using context name in hook_context_load_alter() and tweak it.

/**
 * Implementation of hook_context_load_alter()
 */
function mymodule_context_load_alter(&$context) {
  if ($context->name == 'my_context_name_from_the_ui') {
    $context->reactions['block']['blocks']['my_block_name']['weight'] = -99;
  }
}


Your best bet is to print the class attributes separately, and use the without twig filter, then hard code the IE stuff, e.g.

<!--[if lt IE 9]> <html{{ html_attributes|without('class') }} class="{{ html_attributes.class }} lt-ie10 lt-ie9"> <![endif]-->
<!--[if IE 9]>    <html{{ html_attributes|without('class') }} class="{{ html_attributes.class }} lt-ie10"> <![endif]-->
<!--[if gt IE 9]><!-->
<html{{ html_attributes.addClass('no-js') }}>
<!--<![endif]-->

https://www.drupal.org/node/1823416
https://www.drupal.org/docs/8/theming/twig/filters-modifying-variables-in-twig-templates


How to change the order of fields in the Drupal Commerce Checkout Form

Changing field order on the checkout form can be done by going to admin/commerce/config/checkout

Then just drag the items up and down to arrange them in the order you wish.


Loading views blocks that aren't actively set

See this answer for details.

Basically, the way to do this is to add a "Hidden Blocks" region to your theme, then place the blocks you want to render there.  The region does not get rendered so it's not a big resource drain.  We do this to use have "block" paragraphs using paragraphs all the time.


Including custom functionality with multilingual capabilities from the start

Generally speaking, making a module ready for multilingual use is so incredibly easy when you're building it that it makes a LOT of sense to do it.   Retrofitting would be a real pain in the ass!

I'm not exactly sure what module you're building, but it could be as simple as wrapping any user facing copy with t().


I found it! It was just a stupid typo in the .info file. I should have inserted regions[usermenu] = User menu...


Did you have "Clean URLs" enabled on the Windows install?  You may need mod_rewrite enabled in Apache (a2enmod rewrite)

I'm not sure how your server is configured (os/php version/etc), but I had a similar issue that required me to change the following in .htaccess

# RewriteBase /
to
RewriteBase /

Another thing to check would be that overrides are allowed at all.  Apache needs to be set to something like "AllowOverride All"

More info regarding AllowOverride:

How can I enable clean URLs?

How to enable Clean URLs?

Regarding permissions, there is a bunch of information available including a script that can help repair permissions (obviously use extreme caution when running and verify before you do.)

Source for the script below.

#!/bin/bash

# Help menu
print_help() {
cat <<-HELP
This script is used to fix permissions of a Drupal installation
you need to provide the following arguments:

  1) Path to your Drupal installation.
  2) Username of the user that you want to give files/directories ownership.
  3) HTTPD group name (defaults to www-data for Apache).

Usage: (sudo) bash ${0##*/} --drupal_path=PATH --drupal_user=USER --httpd_group=GROUP
Example: (sudo) bash ${0##*/} --drupal_path=/usr/local/apache2/htdocs --drupal_user=john --httpd_group=www-data
HELP
exit 0
}

if [ $(id -u) != 0 ]; then
  printf "**************************************\n"
  printf "* Error: You must run this with sudo or root*\n"
  printf "**************************************\n"
  print_help
  exit 1
fi

drupal_path=${1%/}
drupal_user=${2}
httpd_group="${3:-www-data}"

# Parse Command Line Arguments
while [ "$#" -gt 0 ]; do
  case "$1" in
    --drupal_path=*)
        drupal_path="${1#*=}"
        ;;
    --drupal_user=*)
        drupal_user="${1#*=}"
        ;;
    --httpd_group=*)
        httpd_group="${1#*=}"
        ;;
    --help) print_help;;
    *)
      printf "***********************************************************\n"
      printf "* Error: Invalid argument, run --help for valid arguments. *\n"
      printf "***********************************************************\n"
      exit 1
  esac
  shift
done

if [ -z "${drupal_path}" ] || [ ! -d "${drupal_path}/sites" ] || [ ! -f "${drupal_path}/core/modules/system/system.module" ] && [ ! -f "${drupal_path}/modules/system/system.module" ]; then
  printf "*********************************************\n"
  printf "* Error: Please provide a valid Drupal path. *\n"
  printf "*********************************************\n"
  print_help
  exit 1
fi

if [ -z "${drupal_user}" ] || [[ $(id -un "${drupal_user}" 2> /dev/null) != "${drupal_user}" ]]; then
  printf "*************************************\n"
  printf "* Error: Please provide a valid user. *\n"
  printf "*************************************\n"
  print_help
  exit 1
fi

cd $drupal_path
printf "Changing ownership of all contents of "${drupal_path}":\n user => "${drupal_user}" \t group => "${httpd_group}"\n"
chown -R ${drupal_user}:${httpd_group} .

printf "Changing permissions of all directories inside "${drupal_path}" to "rwxr-x---"...\n"
find . -type d -exec chmod u=rwx,g=rx,o= '{}' \;

printf "Changing permissions of all files inside "${drupal_path}" to "rw-r-----"...\n"
find . -type f -exec chmod u=rw,g=r,o= '{}' \;

printf "Changing permissions of "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
cd sites
find . -type d -name files -exec chmod ug=rwx,o= '{}' \;

printf "Changing permissions of all files inside all "files" directories in "${drupal_path}/sites" to "rw-rw----"...\n"
printf "Changing permissions of all directories inside all "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
for x in ./*/files; do
  find ${x} -type d -exec chmod ug=rwx,o= '{}' \;
  find ${x} -type f -exec chmod ug=rw,o= '{}' \;
done
echo "Done setting proper permissions on files and directories"


Route logged in user to profile on all request to  node

It sounds like there's some missing detail (e.g. checking the right alias, token data not available, etc.).

A simple way to do this to do a page redirect action on a Drupal is initializing event with conditions, Data comparison  on [site:current-page:path] & negated User has role(s) on [site:current-user]. Then you can check for the Drupal path that's set for your front page (i.e. '/node').

For example:

{ "rules_login_frontpage_redirect" : {
    "LABEL" : "Logged in Frontpage Redirect to Profile Page",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "data_is" : { "data" : [ "site:current-page:path" ], "value" : "node" } }
    ],
    "DO" : [ { "redirect" : { "url" : "user\/[site:current-user:uid]" } } ]
  }
}


Is it possible to define a hook_preprocess function based on entity type such as profile2?

This adapts the Zen theme pattern for node preprocess functions to entities:

<?php

/**
 * Implements template_preprocess_entity().
 *
 * Runs a entity specific preprocess function, if it exists.
 */
function MYTHEME_preprocess_entity(&$variables, $hook) {
  $function = __FUNCTION__ . '_' . $variables['entity_type'];
  if (function_exists($function)) {
    $function($variables, $hook);
  }
}

/**
 * Profile2 specific implementation of template_preprocess_entity().
 */
function MYTHEME_preprocess_entity_profile2(&$variables, $hook) {
}

/**
 * Field Collection specific implementation of template_preprocess_entity().
 */
function MYTHEME_preprocess_entity_field_collection_item(&$variables, $hook) {
}


Recommend nodes based on current node field value in view block

There is a module for that: Similar by Terms

However, it's possible with views as well: Creating list of similar nodes in Drupal 7/Views 3

Alternatively, you can use my configuration:

An example of view block with related nodes based on 'tags'.

Create a block (take a look at screenshots below)
Add a relationship: Taxonomy term: Content using: Tags
Add contextual filter: (field_tags) Content: Nid
When the filter value is NOT available
Provide default value -> Content ID from URL
MORE
check: Exclude
this contextual filter will remove current node from the view
Add contextual filter: Taxonomy term: Term ID
When the filter value is NOT available
Provide default value -> Taxonomy term ID from URL
check: Load default filter from term page
check: Load default filter from node page, that's good for related taxonomy blocks
choose the vocabulary (tags in this case)
Multiple-value handling -> Filter to items that share any term
When the filter value IS available or a default is provided
Specify validation criteria  -> Basic validation
MORE
check:  Allow multiple values
Define the fields (only titles in this case)
Make the view display only distinct items
Other -> Query settings:
check: Distinct
check: Pure distinct

Screenshots:


I'm not sure what kind of answer you are looking for ...

If you just want these files stored remotely, but accessible from drupal you may want to look at these modules:

Filedepot
MediaMover
Migrate

I actually have a similar criteria on a site. Serve pdf file listings from a non-drupal directory to allowed users -- essentially a simple directory listing. Here is how I did it in D7 with a bit of custom coding.

I make a symlink from a remote filesystem into like DRUPAL_SITE_DIR/sites/default/files/REMOTE_MOUNTPOINT
Make a custom module that uses something to scan for files and show them to the enduser. You can use D7 file_scan_directory if you like, I actually opted for Symfony's Finder Component. The advantage to Symfony's finder is things like "show files of X size", "sort by something" or doing more complex search filters (which I will need) or truely different types of remote files (FTP, S3, etc). Example code for a module poorly named "views_fs" can be found in this public Gist.

Hope this info helps.


Where can I download old releases of Drupal?

You can get Drupal 6.20 from the Drupal 6.20 released page.

You can also view a list of all current and previous releases on the Releases for Drupal core page, complete with download links. It goes all the way back to Drupal 4.2.0, which I'm now off to install to see what happens!


How to access the fields in the comment reply page?

I think comment.tpl.php is what you need

however you can also alter the display of comments in the display option on the content type.

look in "admin/structure/types/manage/CONTENT_TYPE_MACHINE_NAME/comment/display"


Previewable email templates is a good module and supports Rules and Tokens.

  The Previewable Email Template (PET) module lets you create email
  templates, with token substitution, which can be previewed by the user
  before sending. The emails can be sent to one or many email addresses
  in a flexible way, and the recipients may or may not be Drupal account
  holders (users).


Programmatically Create an Array of User Objects and Print in Twig Template

Before you can render a list of entities you have to build a render array:

$variables['userList'] = \Drupal::entityTypeManager()
  ->getViewBuilder('user')
  ->viewMultiple($userList, 'compact');

Now Twig is able to render the entities:

{{ userList }}

You don't need |render, because Twig renders arrays automatically.


You can hide and unhide form elements with js. For example you can prepare a popup and deliver it with the main form and then trigger it in js.

You can't generate new elements, because they will be ignored when submitted.

You could build your own form solution with custom js and php code. But this is probably not the best way on the long term.

The best answer to your question, how to build dynamic form solutions, is to investigate, what you can do with a js framework and Rest API.


In Drupal 8 you can do this out of the box. Put a reference field in the parent and target it on the child content type. The label of the field would be "In this section". You can theme the section in a field twig of this specific field, for example field--field-reference.html.twig.

You can nest the entities, but if you reference the same content type and you leave the reference field in the view mode of the child there is a risk of an infinite loop, which will result in a time-out.


How to theme a preprocess function output with a default, without the need of a .tpl file?

I didn't realize that I could simply use drupal_set_message()!

drupal_set_message(t("".$correo." (".$estado.")"), 'status');


how to Display author and date information according to my requirement?

Steps to change the order

Override node.tpl.php in your theme template.
Rename it to node--[content_type_machine_name].tpl.php if you want this for a specific content type.
Remove

code and place it after the Project code field is rendered.

Clear the cache after making the change.

Hope that this helps.


I think here is a option to change default email admin/config/content/webform.


There is a dpq() function in the devel module which seems to fulfill this need.

  Print a SQL string from a DBTNG Query object. Includes quoted arguments.


Modules You Need:

Views
Libraries
Views Slideshow
Cycle JS : Save this js file to /sites/all/libraries/jquery.cycle/ where you have to create 2 directories i.e.  libraries and under that jquery.cycle

Now assuming your content type name is IMAGE with two fields

Title
Image

Add 3 dummy images to your newly created content type IMAGE
Now go to admin/structure/views/import
$view = new view();
$view->name = 'slideshow';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Slideshow';
$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'] = 'Slideshow';
$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'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'slideshow';
$handler->display->display_options['style_options']['slideshow_type'] = 'views_slideshow_cycle';
$handler->display->display_options['style_options']['slideshow_skin'] = 'default';
$handler->display->display_options['style_options']['skin_info'] = array(
  'class' => 'default',
  'name' => 'Default',
  'module' => 'views_slideshow',
  'path' => '',
  'stylesheets' => array(),
);
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_pager']['enable'] = 1;
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_pager']['weight'] = '1';
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_pager']['type'] = 'views_slideshow_pager_fields';
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_pager']['views_slideshow_pager_fields_fields'] = array(
  'field_image' => 'field_image',
  'field_image_1' => 0,
);
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_controls']['weight'] = '1';
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_controls']['type'] = 'views_slideshow_controls_text';
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_slide_counter']['weight'] = '1';
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_pager']['weight'] = '1';
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_pager']['type'] = 'views_slideshow_pager_fields';
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_pager']['views_slideshow_pager_fields_fields'] = array(
  'field_image' => 0,
  'field_image_1' => 0,
);
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_controls']['weight'] = '1';
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_controls']['type'] = 'views_slideshow_controls_text';
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_slide_counter']['weight'] = '1';
$handler->display->display_options['style_options']['views_slideshow_cycle']['timeout'] = '5000';
$handler->display->display_options['style_options']['views_slideshow_cycle']['speed'] = '700';
$handler->display->display_options['style_options']['views_slideshow_cycle']['delay'] = '0';
$handler->display->display_options['style_options']['views_slideshow_cycle']['start_paused'] = 0;
$handler->display->display_options['style_options']['views_slideshow_cycle']['remember_slide_days'] = '1';
$handler->display->display_options['style_options']['views_slideshow_cycle']['items_per_slide'] = '1';
$handler->display->display_options['style_options']['views_slideshow_cycle']['wait_for_image_load_timeout'] = '3000';
$handler->display->display_options['style_options']['views_slideshow_cycle']['cleartype'] = 0;
$handler->display->display_options['style_options']['views_slideshow_cycle']['cleartypenobg'] = 0;
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Image */
$handler->display->display_options['fields']['field_image']['id'] = 'field_image';
$handler->display->display_options['fields']['field_image']['table'] = 'field_data_field_image';
$handler->display->display_options['fields']['field_image']['field'] = 'field_image';
$handler->display->display_options['fields']['field_image']['label'] = '';
$handler->display->display_options['fields']['field_image']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_image']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_image']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_image']['settings'] = array(
  'image_style' => 'thumbnail',
  'image_link' => '',
);
$handler->display->display_options['fields']['field_image']['group_rows'] = FALSE;
$handler->display->display_options['fields']['field_image']['delta_offset'] = '0';
/* Field: Content: Image */
$handler->display->display_options['fields']['field_image_1']['id'] = 'field_image_1';
$handler->display->display_options['fields']['field_image_1']['table'] = 'field_data_field_image';
$handler->display->display_options['fields']['field_image_1']['field'] = 'field_image';
$handler->display->display_options['fields']['field_image_1']['label'] = '';
$handler->display->display_options['fields']['field_image_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_image_1']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_image_1']['settings'] = array(
  'image_style' => '',
  'image_link' => '',
);
$handler->display->display_options['fields']['field_image_1']['group_rows'] = FALSE;
$handler->display->display_options['fields']['field_image_1']['delta_offset'] = '0';
/* 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';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* 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;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'image' => 'image',
);

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

Simply go to your-site/slideshow and Voilà! Feel free to comment if you got stuck or need my help.


200 OK on every page after updating the content

I found the solution: Just uncomment the line containing the RewriteBase / directive in the .htaccess file.


How do I embed a view of comments within a view of nodes using Entity Views Attach (EVA)

It's not really practical to intercalate the rows of one view into another view. Instead, what I would do, would be to create a view with node as its base table, include comments via a relationship, and select "distinct" under query settings in the advanced Views settings column.


You can install Mime Mail or HTML Mail module to enable HTML emails in your Drupal instance.
Then, through configuration translation, you can add dir="rtl" to the container enclosing your Arabic email message.


Is there any backport of "Grouped filters" available in Views 6.x-3.x branch?

Yes you can do it with Advanced Exposed Forms for views 3 version

  Advanced Exposed Forms (AEF) provides fine grained dynamic data
  filtering by allowing the "joining" of views exposed filters into
  groups. AEF provides AND/OR operators between individual exposed
  filters and between groups of exposed filters. Use AEF to drill down
  from large amounts of data to specific data sets.


Importing and using overlay from jquery_plugin module

Actually this module seems to be abandoned. Using drupal_add_library() works only if the module used hook_library(). I wanted to check it in the repository of jquery_plugin, but these files aren't available. I don't know why.

If you want to use overlays, you can use directly the jQuery UI that is already included in Drupal 7.


Rendering fields with node display settings

The content array should already contain an element for each field with the display settings applied. You can just print that directly:

<?php print render($content['field_date']); ?>


In search_autocomplete.view_autocomplete.inc file, line number 209 just replace it with the following line:

$object->label .= ' ';

that will remove the label (title) in search result.


How to remove 'error' class from form field?

_form_set_class() is called from a bunch of different theme functions, including

theme_checkbox()
theme_fieldset()
theme_file()

(the rest are here)

You can override whichever of those functions you need to in your theme by renaming the function as (e.g.)

function MYTHEME_checkbox($vars) {

Then copy in the original code from the function, remove the call to _form_get_class(), and replace it with whatever makes sense for your use case.


How to speed up event confirmation email?

Courier message dispatch is all done in cron. Therefore, in order to speed up the delivery of messages, you should run cron as often as possible.

Personally I run it every 30 seconds, but every 1-5 minutes should be fine in most cases.

Disclaimer: I am the maintainer of both the RNG and the Courier modules.


Block content returns no results for anonymus user only

There are multiple layers of permissions which might responsible for this,trying to cover some of them if that helps you.

Check right in the views configuration page and check "access" should be set to "view publish content".
Ensure you are not having contrib module like block_access or custom code which is putting a check the block view on user role basis.
Ensure if you are using contentaccess module or nodeaccess module and they are not letting the block visible to anonymous user.


How to Make Managed File Field Available to Twig Template?

Since my rep isn't high enough to comment... yet, I have to add my comment as an answer.

My initial thought is that the file would be saved as an entity.  After reading up a bit on some d.o comments, there is/was a bug where managed_files are temporary by default.  Somewhere in the mix you'll need to add something similar to

   $image = $form_state->getValue('image');
   $file = \Drupal\file\Entity\File::load( $image[0] );
   $file->setPermanent();
   $file->save();

to make the file permanent.
(credit to This question)

Most likely you will need to save the file itself as an entity in the blockSubmit function.

    $file = \Drupal\file\Entity\File::load($image_id[0]);
    // Change status to permanent.
    if(gettype($file) == 'object'){
      $file->setPermanent();
      // Save.
      $file->save();
      $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
      $file->setOwner($user);
    } ... and so on.

After that, you should be able to pass the filename or file entity to your theme layer and load it in your preferred method.

Examples modified from This d.o post


Alternative ways to clear the Drupal cache

While your cache bins are in MySQL, truncating tables is by far and away the quickest method to clear the cache. It's not a particularly expensive operation, so if it's backing up your db connections I would get your sysadmin to investigate what config issues might be causing that (or whether it's simply a lack of sufficient resources).

As MPD notes in the comments above, your real problem might actually be the cache rebuild after the flush has happened, though. You should be able to confirm that after a bit of testing.

You can take the pressure off the database by using redis/memcache/etc as a cache backend instead of the database. Doing that will also make considerable speed improvements to your site in general.

Your mileage will vary, of course, but it's very likely that flushing cache from memory will be a quicker operation than flushing it from the disk. As Mołot notes below, writing the new cache items to memory rather than disk will also give you a performance boost (there will still be reads and writes to MySQL, but far fewer writes in theory).

As with anything, it needs testing on the bare metal to see how any of this would affect your specific configuration.


db_select() which selects nodes which have a certain term

saadlulu's answer is also correct, but since it doesn't specifically address the topic of taxonomy terms, I want to post my solution which I got working just a few minutes ago and explain what is happening so that some other newbie who comes along can understand what is happening well enough to alter it for their own uses.

My nodes are of type photo_gallery and they have a taxonomy terms field called field_tags and I want to grab all of the nodes which have the term for $term_id

$query = db_select('node', 'n');
$query->join('field_data_field_tags', 't', 't.entity_id=n.nid');
$result = $query
  ->fields('n', array('nid', 'title', 'created'))
  ->fields('t', array('entity_type', 'bundle', 'field_tags_tid', 'entity_id'))
  ->condition('entity_type', 'node')
  ->condition('bundle', 'photo_gallery')
  ->condition('field_tags_tid', $term_id)
  ->condition('status', 1)
  ->condition('type', 'photo_gallery')
  ->orderBy('created', 'DESC')
  ->execute();

The part I didn't know/understand was how the tables were structured behind the scenes for things like a term reference. When I looked into the actual SQL tables, then it became clear. The connections between a node and a taxonomy term are stored in a separate table and knowing which table that is was one of the big questions.

So, my field_tags data is stored in the field_data_field_tags table. I grabbed the nid of one of my nodes to see what the data looked like.

mysql> select * from field_data_field_tags where entity_id=1082;
+-------------+---------------+---------+-----------+-------------+----------+-------+----------------+
| entity_type | bundle        | deleted | entity_id | revision_id | language | delta | field_tags_tid |
+-------------+---------------+---------+-----------+-------------+----------+-------+----------------+
| node        | photo_gallery |       0 |      1082 |        1082 | und      |     0 |              5 |
+-------------+---------------+---------+-----------+-------------+----------+-------+----------------+
1 row in set (0.00 sec)

Once I understood the info above, then I could see that I needed to join to the field_data_field_tags table and do that join on entity_id=nid.


Is the a module that will allow me to quickly switch from administrator to user?

You can use masquerade module.
Part of description :

The Masquerade module allows site administrators (or anyone with
enough permissions) to switch users and surf the site as that user (no
password required). That person can switch back to their own user
account at any time.
This is helpful for site developers when trying to determine what a
client, logged in as themselves, might see when logged into the site.
The masquerade module is designed as a tool for site designers and
site administrators. While masquerading, a field is set on the $user
object, and a menu item appears allowing the user to switch back.
Database log (watchdog) entries are made any time a user masquerades
or stops masquerading as another user.


The Webform Ajax module will give you the functionality you describe. Here is a quote about it (from the module's project page):

... adds AJAX support to Webform (3.0 and above).
As a first step it focusses to simply add form AJAX paging and submit. Form submissions get ajaxified including prev/next pages. Especially for multipage forms, this leads to faster loading (less data transfer), better usability and finally smaller server load.