How do I alter the text of the input field in the search form? I need to alter the text of the search input field. In my quest to do this, I have  dpm() the content of $form on a call to hook_form_search_box_form_alter(). The output is the following.

Array
(
    [search_block_form] => Array
        (
            [#type] => textfield
            [#title] => Search
            [#title_display] => invisible
            [#size] => 15
            [#default_value] =>
            [#attributes] => Array
                (
                    [title] => Enter the terms you wish to search for.
                )

        )

    [actions] => Array
        (
            [#type] => actions
            [submit] => Array
                (
                    [#type] => submit
                    [#value] => Search
                )

        )

    [#submit] => Array
        (
            [0] => search_box_form_submit
        )

    [#form_id] => search_block_form
    [#type] => form
    [#build_id] => form-Y0XlzH4YO-EqVHxg5wnRf-PrnecuUSGdo5LTCPcLgLU
    [form_build_id] => Array
        (
            [#type] => hidden
            [#value] => form-Y0XlzH4YO-EqVHxg5wnRf-PrnecuUSGdo5LTCPcLgLU
            [#id] => form-Y0XlzH4YO-EqVHxg5wnRf-PrnecuUSGdo5LTCPcLgLU
            [#name] => form_build_id
            [#parents] => Array
                (
                    [0] => form_build_id
                )

        )

    [form_id] => Array
        (
            [#type] => hidden
            [#value] => search_block_form
            [#id] => edit-search-block-form
            [#parents] => Array
                (
                    [0] => form_id
                )

        )

    [#id] => search-block-form
    [#method] => post
    [#action] => /
    [#theme_wrappers] => Array
        (
            [0] => form
        )

    [#tree] =>
    [#parents] => Array
        (
        )

    [#validate] => Array
        (
        )

    [#theme] => Array
        (
            [0] => search_block_form
            [1] => search_box
        )

)

Is $form['search_block_form']['#title'] = ''; the right thing to do here?

@NoSssweat has provided a link, it is the answer if you want to alter a placeholder.

But reading your question I am getting other indications also.

FOR D7:

Case-1: If I read the sentence from your question "I need to alter the text of the search input field" I think you are talking about the placeholder, Now what is placeholder- you can see in following image the word "Search the site" in the text-area is called place-holder.

Case-2: But if I read your last sentence, "Is $form['search_block_form']['#title'] = ''; the right thing to do here?" then it talks about other things, this is corrosponds to Text appear when you hover on the input text-area("Enter the terms you wish to search for") as shown in following image.

I will explain both of that, The best tutorial for this is available here: How to Customize the Block Search Form.

Case-1 Paste the following code in your theme's template.php file, change the YourThemeName with your actual theme-name, save & clear the cache.

function YourThemeName_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    $form['search_block_form']['#attributes']['placeholder'] = t('Search the site');
}

Case-2

function YourThemeName_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    $form['search_block_form']['#attributes']['title'] = t('Place a new sentence');
}

Case-3: If you want title on the block, you can just go to block configuration and put the title whatever you want, it will appear as a title of the Block.

FOR D8: as @NoSssweat pointed out in the following comment, how to do in D8. Hence, I am just repeating that comment here as it is needed.

function YourThemeNAme_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
  $form['keys']['#attributes']['placeholder'] = t('The new placeholder');
}


Split commerce cart to multiple orders per product What's a solution in Drupal Commerce to create an order per product in cart during the checkout?

The cart looks like this:

Product A, Quantity: 2, $100
Product B, Quantity: 1, $199

Total: $399

The order-output should be:

Order #1: Product A, Quantity: 2, $100, Total: $200
Order #2: Product B, Quantity: 1, $199

So instead of the usually created single order that contains all products in the cart, the goal is to create an order per product in the cart.

Could a checkout rule solve this? Or a custom module, and if, how?

As you now,by default drupal add to cart form add all products to the same order.

Looking at the code of commerce_cart.module, the base and unique behaviour of commerce_cart module, it doesn't works in other way. When a product is add to cart, the order associated will be the same order or a new order.

If you want to decouple the line items in two different orders in cart page you will have to code a module based in commerce cart with that feature.

You can take a look to this module, it maybe helps you https://www.drupal.org/project/commerce_cart_multiple


Only a view filters in exposed filter block I have a view with 7 exposed filters in an exposed filters block.

But I only want to have 2 filters in the exposed form block. All 7 filters I want to have on the views page.

Is there another solution then display: none?

You could copy the view for your second use case and only make the 2 needed filters exposed and expose that as a block.


how to get the count of total comments posted for specific content type including deleted comments too? I want to get the total count of comments posted only for a specific content type including deleted to get the highest comment id no matter whether comment is been deleted. please help me or else suggest me other way to achieve this.

You can always dig around the database with a db query with something like:

$content_type = 'mycontenttype';
$query = db_select('comment', 'c');

$query->join('node', 'n', 'n.nid = c.nid'); //JOIN node with comment
$query->fields('c', array('cid')); //SELECT the fields from comment
$query->condition('n.type', $content_type, '=');
$query->orderBy('c.cid', 'DESC'); //ORDER BY comment id

$num_comments = $query->countQuery()->execute()->fetchField();
$latest_comment_cid = $query->execute()->fetchField();

EDIT
In this example I assume you mean unpublished comments and not deleted. See Anil's answer if you want to track count of deleted comments as well.


How do I keep unique form id for ajaxified form? I have a form(which is extending the FormBase class) that requires entity as argument(but I am not manipulating with this entity so that's why I am not using the EntityForm which is irrelevant to this issue but just FYI). The form uses data from the entity to build the form id. I am instantiating the form as object and I am keeping the entity as property on the form.

Due to the fact that I have multiple such forms on a single page I need the form id to be unique and matching the provided entity object to avoid collision of submitted values. In Drupal 7 this was taken care of via hook_forms().

Now I want to ajaxify this form but there is an issue that after the first submission the entity object is no longer available to the form. I have stored the data I need in the $form_state but I cannot access this in the getFormId() method.

So I have made the form id non-unique and each form instance has the same id. I have tried to get around this issue by setting the form id in the form array itself as #id attribute but that did not helped.

So my question is how to have an ajaxified form with unique form id that is based on data from provided argument to the form?

This is how I am invoking the form(in lazy loader):

$entity = $this->entityManager->getStorage($entity_type)->load($entity_id);
$form = new MyForm($entity);
return $this->formBuilder->getForm($form);

and the form itself:

class MyForm extends FormBase {

  private $entity;

  public function __construct($entity) {
    $this->entity = $entity;
  }

  public function getFormId() {
    return 'my_form_' . $this->entity->getEntityTypeId() . '_' . $this->entity->id();
  }

}

So the issue was that I was calling the getFormId() in the form itself to build the html id for the ajax wrapper. For rebuilt form the entity object that I provided as argument to constructor was not available anymore so calling this method caused it to look for that entity object to extract data to build the id from and since it no longer exists it caused this issue.


How to style/theme an openlayers map block? I can't seem to figure out how to target the block that my OpenLayers map sits in. I've switched from a Gmap to an OpenLayers implementation, so I already know which styles I want to apply to the Map block itself, but when I mess with the styles in chromes dev tools I get strange results such that my points and map controls get moved, but not the map container itself

So applying the styling to the map block directly in dev tools result in the base-layer being pushed off and inaccurate. It looks like the map block and div id's get generated by the javascript in openlayers on each page load, so I'm not sure exactly how or where to apply my CSS. I get similar results when I target the map container div as well.

This the css I was applying to the Gmap

#block-views-phi-rho-chapter-map-block-1 {
  width: 95%;
  margin-left: auto;
  margin-right: auto;
}
@media all and (min-width: 720px) {
  #block-views-phi-rho-chapter-map-block-1 {
    width: 85%;
  }
}
    .view-phi-rho-chapter-map {
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  border: 10px solid #dbdbdb;
}

ok, so the answer should have been more obvious to me but I'm not really a front-end guy so it took a little head scratching to see that I just had to target the block by class rather than id...


How do I show a block in a region? All blocks in the footer region use a CSS grid system. I want to add a <div> with CSS attributes to each (custom) block in the footer. The code I have will show the blocks in the footer, but will give an error. Changing {{ key }} to {{ key.content }} is not helping. I am using Drupal 8.6.8.

The code that I am using in the page.html.twig template is the following.

{% for key in page.footer %}
    <div class="col col-4">
        {{ key }}
    </div>
{% endfor %}

Using that code, I get this error message.

  User error: "0" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core\lib\Drupal\Core\Render\Element.php).

Remove array keys starting with '#':

{% for key, block in page.footer if key|first != '#' %}
    <div class="col col-4">
        {{ block }}
    </div>
{% endfor %}


How to remove the "Add new Comment" link from book pages I have created two books, and both of them have child pages (which are also book pages). I have activated the option of commenting, in which the comment box is shown in the same book page.

All works fine when there is no comment on a particular page, but even when any user posts at least one comment on the page, the "Add New Comment" button appears in the links area below page-links and above the comment-wrapper; the comment box is shown below. I just wanted to ask how to remove this link because it is messing with the other options in the links area (e.g. printer friendly page, PDF).

I did create a hook using the following code.

<?php
  /**
  * Implementation of hook_link_alter
  * Remove add comment link from a content type
  * MODULENAME = remove_comment
  **/
  function MODULENAME_link_alter(&$links, $node){
    if($node->type == 'book'){
      unset($links['comment_add']);
    }
  }
?>

I have set the permissions for the users to post comments and have kept the comment box open by default. So, it makes no sense in having the Add new comment link.

And in admin/structure/types/manage/book, the settings are as shown below.

I did get the solution and was able to remove the "Add new comment" link, from the links area. I just went to comment module and commented the following lines of code on line #675.

// Show the "post comment" link if the form is on another page, or
// if there are existing comments that the link will skip past.
if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE || (!empty($node->comment_count) && user_access('access comments'))) {
  $links['comment-add'] = array(
    'title' => t('Add new comment'),
    'attributes' => array('title' => t('Share your thoughts and opinions related to this posting.')),
    'href' => "node/$node->nid",
    'fragment' => 'comment-form',
  );
  if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) {
    $links['comment-add']['href'] = "comment/reply/$node->nid";
  }
}

I know it is not recommended to modify the core. I have implemented a hook to remove the link.

Solution found
The following hook in my custom module works for me :)

function MODULENAME_node_view_alter(&$build) {
  if ($build['#node']->type == 'book') {
    unset($build['links']['comment']['#links']['comment-add']);
  }
}


Multigroup (CCK3) / FlexiField-like solution for compound fields? I've used FlexiField in the past to do multiply occurring series of field groups; now, working on a Drupal 7 project, I'm setting up a "Resume" content type and need a way to set up repetitive entries for education/work experience.

IE: for "Education", I need the ability to dynamically add new rows comprised of a combination of dates and places for each institution studied at.

What is the best way to accomplish CCK3 multigroup/FlexiField-like functionality in Drupal 7?

Thanks!

For the moment, I'm implementing this via Field collection. Granted, that is still very early development.

If somebody could provide a list of solutions in the "group content fields together and allow an infinite number of these groups via the 'add another' button", I'll accept that as my answer. I may have to upgrade my FlexiField project to D7 at some point and there's currently no clear upgrade path with that module.


What entity type should I choose for a comment type? When I add a comment type (for example, Blog comments), I can select an entity type as target for the comment.
What should I choose and why?
Is it Custom block or Comment? My intuition says to pick Comment, but I don't know on what basis I should decide what to pick.
The other option seems in any case less likely for my case. I just need a global article comment type.

That depends to which entity you want to attach those comments. If the new comment type is for content types (node bundles), select the according type. (I assume it's one of the the last three list entries given in your screenshot.)


Login form - hook_form_alter destinations broken I have a custom log in template along with some alterations. It seems to work just fine everywhere except where I have ...?destination=foo/bar.

The template code is:

    <?php print render(drupal_get_form('user_login', $form)); ?>

Don't have an account? Register now

    <?php print render(drupal_get_form('user_register_form')); ?>

The module code is:

function fdanconia_menu(){
  $items['login'] = array(
    'title' => 'Login',
    'page callback' => '_fdanconia_login',
    'access callback' => true,
  );
  return $items;
}

function fdanconia_theme(){
  $themes = array(
    'fdanconia_login' => array(
      'template' => 'fdanconia_login',
      'arguments' => array(),
    ),
  );
  return $themes;
}

function fdanconia_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  switch ($form_id) {
    case 'user_login':
      // Redirect users to the new login page
      if (isset($_GET['destination']) && $destination = $_GET['destination']) {
        $options = array('query' => array('destination' => $destination));
        unset($_GET['destination']);
      } else {
        $options = array();
      }
      if (arg(0) == 'user' && !$user->uid) drupal_goto('login', $options);
      $form['name']['#description'] = 'Email';
      $form['pass']['#description'] = 'Password';
    break;
    case 'user_register_form':
      if (arg(0) == 'user' && !$user->uid) drupal_goto('login', array('query' => array('destination' => $destination)));
      $form['account']['name']['#type'] = 'hidden';
      array_unshift($form['#validate'], '_fdanconia_login_validate');
    break;
  }
}

function _fdanconia_login() {
  drupal_add_css(drupal_get_path('module', 'fdanconia') . '/fdanconia.css');
  drupal_add_js(drupal_get_path('module', 'fdanconia') . '/fda.js', 'file');
  return theme('fdanconia_login');
}

function _fdanconia_login_validate($form, &$form_state) {
  $email = $form_state['values']['mail'];
  $form_state['input']['name'] = $email;
  $form_state['values']['name'] = $email;
  $form_state['complete form']['account']['name']['value'] = $email;
}

So, when I log in with a destination no matter what it redirects to the default log in page as if there were no destination parameter. However, the destination shows up in the URL. I can even manually put a destination in the URL and when I submit the form, I am not redirected to the proper destination. There is nothing in watchdog about the log in other than a session has been created.

What is going wrong here?

I think in D7 you can also use the redirect property, this would be in your form_alter:

  $form_state['redirect'] = array('http://www.example.com/my-external-path', array('external' => TRUE));

$form_state['redirect'] takes the same values as drupal_goto(), which itself uses url() to generate its destination path. It is possible to add an array of options including 'external=TRUE' to your redirect value if redirect is external.

Not sure if this will help in your case though.


Is there a more performant alternative than overriding template files? I've got to get rid of a lot of unnecessary markup in a view. In general, I accomplish that by overriding the template files in my theme, but this time the view is really huge and performance is going down. So I wondered, if there's a more performant way to reduce markup? When altering the markup of a node, than preprocess functions are faster then overriding template files, is there an analogical mechanism for views?

Edit 1: Sure, the reason for the weak performance is not the overriding of template files on the first place, but if I can optimize a bit there, I'll have to do that. In addition I regularily get into trouble by disabling markup in views UI itself: disableing row-styles for example is ignored when I use an Omega subtheme …

Edit 2: I am aware of the possibilities inside the Views UI; What I am looking for is a manual way with fine control.

You can eliminate unnecessary markup through the Views UI.

When you add a field, hidden under Style Settings, they always have this default unnecessary checkmark

Also, you can remove more markup here

and here


Can someone explain the @RestResource annotation for building a Rest resource? I am trying to create a RESTful web service.  Above the class there is the following  comment.

/**
 * Represents entities as resources.
 *
 * @RestResource(
 *   id = "entity",
 *   label = @Translation("Entity"),
 *   serialization_class = "Drupal\Core\Entity\Entity",
 *   deriver = "Drupal\rest\Plugin\Deriver\EntityDeriver",
 *   uri_paths = {
 *     "canonical" = "/entity/{entity_type}/{entity}",
 *     "https://www.drupal.org/link-relations/create" = "/entity/{entity_type}"
 *   }
 * )
 *
 * @see \Drupal\rest\Plugin\Derivative\EntityDerivative
 */

What does this mean? What is it supposed to do?

I can't find anything useful about this, especially about the uri_paths array.

Annotations are used in Drupal 8 to provide meta data in the same location as the class definition. It was borrowed directly from Symfony which is used in the Drupal 8 core to take advantage of an existing framework. The meta data is contained from the lines between @RestResource( and the closing ). Everything else is treated as a normal php block comment. For example I have a custom REST resource for which the annotation is:

/**
 * Provides a resource for database intermed table entries.
 *
 * @RestResource(
 *   id = "intermed",
 *   label = @Translation("Intermed content entity standard methods"),
 *   serialization_class = "Drupal\intermed\Entity\Intermed",
 *   uri_paths = {
 *     "canonical" = "/intermed/{intermed}",
 *     "http://drupal.org/link-relations/create" = "/entity/intermed"
 *   }
 * )
 */

So for this resource intermed is the id and is used in request operations. The canonical form /intermed/{intermed} will be used for operations other than POST which uses /entity/intermed

In the canonical setting the {intermed} denotes a parameter to be passed.

So if I was to send a GET request to site d8beta14.qetm.org as format HAL+JSON for the intermed table entry for which the id was 2:

GET http://d8beta14.qetm.org/intermed/2?_format=hal_json

This GET operation requires three headers: Authorization, Accept, Content-Type


Acquia Dev Desktop Redirects to Live Site I have a weird thing happening - I took a copy of my live site, and a dump of my database, and imported it into the Acquia Dev Desktop application to run a dev site locally. This site has worked in this manner in the past. However, when I do this now, visiting the local path (ex. localhost:8082) redirects to my live site out on the web. I believe it's something in the database, as running the code with a standard Acquia database works, but as soon as I swap in the database from my live site the redirect occurs.

Any ideas what could be causing this?? I don't have anything in rules or actions to redirect anything, and I don't know what else it would be.

I encountered this problem tody, and it turns out that the securepages module causes it. After disable that module, everythin works.

Though, don't forget to enable the module before going online.


How should I upgrade a customized theme? I have made some custom changes to my theme files template, CSS and tpl files. Is there a best practice method of updating the theme besides going line by line and re-inserting my custom changes after uploading the new theme?
Is there a better way to approach this in the future?

You asked "Is there a better way to approach this in the future?".

An alternative to modifying the theme you're basing things on (which I favour) is subthemeing, with which you extend the existing theme by overriding only the aspects you wish to change. This allows you to upgrade the original theme and retain your code separately.

http://drupal.org/node/441088 Quick and Dirty Subthemeing
http://drupal.org/node/225125 Subtheme structure and inheritance

This approach isn't entirely a free pass against maintenance, though.

If a fix is applied to the core theme and you've copied the (previously broken) code to your subtheme, then you'll retain the broken code as an override.
If a change is made to the base theme which your subtheme doesn't account for, you'll need to handle that.

So - you will still need to review updates to the core theme, but this approach (for me) makes the most sense, means I'm maintaining the smallest amount of code, and provides a fairly straightforward way to build on the existing themes Drupal offers.


Drupal 8 - how do I extrat the URL path from node title I can print title of my content-type using {{ fields.title.content }}. and it renders like Title of the content. I have created a View (view mode: field) and showing a list of available products on that page. To customize look and feel of the page I copied views-view-fields.html.twig file from core/themes/stable/template/views under my theme's template directory and customized it the following way.

        {{ fields.field_product_image.content }}

{{ fields.title.content }}

{{ fields.field_product_summary.content|striptags|convert_encoding('UTF-8', 'HTML-ENTITIES') }}

        {{ fields.field_category.content }}&nbsp;|&nbsp;
        Price: {{ fields.field_product_price.content }}&nbsp;
        View &raquo;

The title itself is linked to product's page. But I have an additional View button which I want to link to the product page separately as well. In order to accomplish the same I tried to extract the URL part from the title with {{ path('entity.node.canonical', { 'node' : node.id}) }}. But it gives me the following error message.

  Symfony\Component\Routing\Exception\InvalidParameterException: Parameter "node" for route "entity.node.canonical" must match "\d+" ("" given) to generate a corresponding URL. in Drupal\Core\Routing\UrlGenerator->doGenerate() (line 193 of core\lib\Drupal\Core\Routing\UrlGenerator.php).

I am referring to this article:
https://chromatichq.com/blog/creating-links-within-twig-templates-using-path-and-url

What I did wrong?

This is what I want to achieve:

I used {{ dump(fields.title.content) }} to see if I the URL could be accessible, but there was nothing like it.

Try {{ path('entity.node.canonical', { 'node' : row.nid}) }}. Also it is better to use kint or devel_dump for twig debug.


SQL injection Drupal Core - Highly Critical - Public Service announcement - PSA-2014-003 issue I got this news today about  SA-CORE-2014-005 - Drupal core - SQL injection.

We are not using drupal in build authentication. We have a custom authentication, which resides behind SSO and gateway. A user can only get access or even get access page if the user is the in SSO and Gateway servers.

Is this kind of setting also vulnerable to this attack, as access is not handled by drupal?

Yes, your site is vulnerable. If your network is stopping people accessing the Drupal site without prior authentication then you're (potentially) safe from those outside the network, but still vulnerable to those inside it.

As with all security issues, upgrade as soon as physically possible.


Custom node migration for multi-value imagefield I'm working on a custom migration module to "link" images to the imagefield.
It's work well for an unique value image field like this:

field_illus_vdl:
  -
    plugin: d6_field_file
    source: field_illus_vdl
    migration: upgrade_d6_file
  -
    plugin: skip_on_empty
    method: process

But not for a multivalue imagefield after different tests:

field_galerie_image_vdl:
  -
    plugin: skip_on_empty
    method: process
  -
    plugin: sub_process
    source: field_galerie_image_vdl
    process:
      target_id:
        plugin: migration_lookup
        migration: d6_file (upgrade_d6_file doesn't change result)
        source: fid
      alt: alt
      title: title
      description: description

I try with iterator plugin, but no change.What is missing or wrong ? Do order is important between for chained processes ?

thanks

EDIT: I see there that sub_process replace iterator plugin.But I don't find infos about a cckfield plugin.

Devel data example:

field_galerie_image_vdl (Array, 6 elements)
0 (Array, 10 elements)
1 (Array, 10 elements)
fid (String, 4 characters ) 2006
uid (String, 1 characters ) 8
filename (String, 11 characters ) niger_3.jpg
filepath (String, 48 characters ) sites/all/media/galerie/actu/2018/20/niger_3.jpg
filemime (String, 10 characters ) image/jpeg
filesize (String, 6 characters ) 113504
status (String, 1 characters ) 1
timestamp (String, 10 characters ) 1526837277
list (String, 1 characters ) 1
data (Array, 3 elements)
description (String, 0 characters )
alt (String, 0 characters )
title (String, 0 characters )

Extract of a value for a filefield from var_dump:

[field_illus_vdl] => Array
    (
        [0] => Array
            (
                [fid] => 2004
                [uid] => 8
                [filename] => niger4.jpg
                [filepath] => sites/all/media/illustration_vdl/2018/20/niger4.jpg
                [filemime] => image/jpeg
                [filesize] => 181770
                [status] => 1
                [timestamp] => 1526837126
                [list] => 1
                [data] => Array
                    (
                        [alt] => Lycée Célony - Aix en provence
                        [title] => Lycée Célony
                    )

                [nid] => 471
                [view] => Lycée Célony - Aix en provence
            )

    )

This source could be the right way,but I can't it work actually.

EDIT2: an format error in my YML file break the process, so after reorder the file, files are migrated.With a more simple code too:

 field_galerie_image_vdl:
  -
    plugin: d6_field_file
    source: field_galerie_image_vdl
    migration: upgrade_d6_file
  -
    plugin: skip_on_empty
    method: process

I think your problem come from source migrate. When you using process sub_process source data must be an array like this:

[
    'fid' => 1,
    'another_key' => '...'
],
[
    'fid' => 2,
    'another_key' => '...'
],
[
    'fid' => 23,
    'another_key' => '...'
]

Note: fid is old fid of database need to migrate.

I'll show you a example migrate field image with multilple value. I have a content type with machine name galary. This content type have body and field images (machine_name: field_images) ullimited value.

I'll migrate data to this content. Create migration group galary with file name migrate_plus.migration_group.galary.yml and content

id: galary
label: Import galary images
description: Import field images has multilple values.

Create migration file_images with file name migrate_plus.migration.file_images.yml

id: file_images
label: 'Migrate images files'
migration_group: galary
source:
  constants:
    file_destination: 'public://galary/'
  plugin: embedded_data
  data_rows:
    -
      fid: 1
      alt: 'Bootstrap'
      src: 'https://www.drupal.org/files/styles/grid-3/public/project-images/bootstrap_project_1.png'
      filename: 'bootstrap_project_1.png'
    -
      fid: 2
      alt: 'Adminimal - Responsive Administration Theme'
      src: 'https://www.drupal.org/files/adminimal-logo-slogan.png'
      filename: 'adminimal-logo-slogan.png'
    -
      fid: 3
      alt: 'AdaptiveTheme'
      src: 'https://www.drupal.org/files/styles/grid-3/public/project-images/Adaptivethemes_220.png'
      filename: 'Adaptivethemes_220.png'
    -
      fid: 4
      alt: 'Drupal8 Zymphonies Theme'
      src: 'https://www.drupal.org/files/styles/grid-3/public/project-images/desktop_8.png'
      filename: 'desktop_8.png'
  ids:
    fid:
      type: integer
process:
  public_path:
    -
      plugin: concat
      delimiter: ''
      source:
        - constants/file_destination
        - filename
    -
      plugin: urlencode
  uri:
    plugin: file_copy
    source:
      - src
      - '@public_path'
destination:
  plugin: entity:file

Create migration node_images with file name migrate_plus.migration.node_images.yml and content

id: node_images
label: Node galaryy
migration_group: galary
source:
  plugin: embedded_data
  data_rows:
    -
      nid: 1
      title: 'Bootstrap'
      body: 'Body Bootstrap'
      images: 1|3
    -
      nid: 2
      title: 'Adminimal - Responsive Administration Theme'
      body: 'Body Adminimal - Responsive Administration Theme'
      images: 2|4
  ids:
    nid:
      type: integer
destination:
  plugin: entity:node
  default_bundle: galary
process:
  title: title
  'body/0/value': body
  'body/0/format':
    plugin: default_value
    default_value: basic_html
  field_images:
    plugin: sub_process
    source: images
    process:
      target_id:
        plugin: migration_lookup
        migration: file_images
        source: fid
migration_dependencies:
  required:
    - file_images

In my case, two source file_images and node_images I use the embedded_data source plugin for the sake of simplicity so that this example can be copy-pasted as a working example.

Let see images: 2|4 or images: 1|3 in data_rows.
I'll use source: images for process sub_process plugin but data is not like data example. So I need use hook_migrate_prepare_row or method prepareRow in your source plugin to prepare soure.

/**
 * Implements hook_migrate_MIGRATION_ID_prepare_row().
 */
function MODULE_NAME_migrate_node_images_prepare_row(Row $row, MigrateSourceInterface $source, MigrationInterface $migration) {
  $images = $row->getSourceProperty('images');
  $images = explode('|', $images);
  $data = [];
  foreach ($images as $index => $fid) {
    $data[$index] = ['fid' => $fid];
  }
  $row->setSourceProperty('images', $data);
}

Now, you can import data to this content have multiple field images with

drush mim file_images && drush mim node_images


After migrating D6 only homepage works I've migrated a D6 site to a new server and now it's working in a very strange way:

Homepage loads OK
Update.php and install.php loads OK
Any other page (including /admin, /user...) doesn't work. They load but they all show the homepage content instead of the content of that page.

You can see it live in http://www.efetic.com/

I'm not able to access /user, so I can't change any configuration, clear cache, etc. I've ran update.php but it doesn't change anything.

I've read some related issues and most seem to point it should be an Apache/htaccess error. I'm not using apache, but nginx. I don't know much about nginx, but I have other drupal sites working correctly in this same server (although they are all D7, not D6 like this one).

What do you think? It's a Drupal problem or an Nginx problem?
Should I ask in Stackoverflow or Serverfault?

Check if your server supports Clean URLs. It is most likely the culprit.

You can consult the following threads on how to enable Clean URLs on Nginx.

Clean URLs on Nginx
Enabling Clean URLs on Nginx(Stackexchange)


Feeds importer pass header values when fetching feed We have been importing nodes with feeds importer from XML for awhile on this website and now the feed has been changed to a new XML but this time it's password/username protected. The XML feed is literally the same with the exception of a couple new fields.

When I used this XML feed inside of a custom module, I simply pass the username/password into a header of the curl call to authenticate. I currently cannot find the appropriate area to pass header values in within feeds import.

My question would be, is there any support for username/password authentication when pulling in a XML file with a HTTP Fetcher, with Feeds import? Are there any contrib modules that could extend feeds importer to provide the functionality i desire?

feeds httpfetcher append headers was the module I needed. Once i switched the fetcher I was able to pass in the password & user name into the get request to authenticate the request.


Redirect to checkout after pressing the "Add to Cart" button When a user presses the "add to cart" button on a product page, I want to automatically redirect the user to the checkout page.

Drupal 7 has an issue for doing this programatically and an issue for doing this with the Rules module.

Rules is still in alpha for D8, and I tried to make a rule that acts on after saving a new order, but I'm getting an error when I try to add an action:

Error: Call to a member function getDataType() on null in Drupal\rules\Plugin\RulesAction\EntityCreateDeriver->getDerivativeDefinitions() (line 99 of modules/contrib/rules/src/Plugin/RulesAction/EntityCreateDeriver.php).

So I want to redirect from add to cart to the checkout page programatically.

But there is no documentation yet.  So if anyone can explain how to do this, I would be much obliged.

you could do something like this:

use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;

function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (strpos($form_id, 'commerce_order_item_add_to_cart_form_commerce_product') !== false) {
    $form['actions']['submit']['#submit'][] = 'MYMODULE_cart_alter_sub';
 }
}
function MYMODULE_cart_alter_sub(&$form, FormStateInterface $form_state) {
  $responce =  new RedirectResponse('/cart');
  $responce->send();
}


Is there a D7 equivalent to the Unlimited Field module? I need a field allowing either a numeric value or "unlimited".

The Unlimited Number module is exactly what I want, but it's D8-only.

Is there a way to do the same thing in D7?

To implement a field allowing either a numeric value or "unlimited" in D7, you can define such field using the desired widget (like a textfield maybe?). And then use the Rules module to validate the actual data that is entered before the entity (like a node or user where you use that field?) is saved (created or updated).

Some more details about the validation part of such rules to be created:

Add the appropriate validations you want within the Rules Conditions.
You may want to specify multiple conditions and combine them with an "OR", eg to validate that the value entered is either the string "unlimited", or a digit equal to "0", "1", "2", "3" or "4".
If you have lots of allowed digits (say dozens), just use an appropriate regular expression (instead of a loooong list of digits).

Have a look at my answer to "How to make the permissions of a module more granular?", which you can use as examples of what might be needed to implement Rules conditions as in bullets "2." or "3." above.

Of course you'd also have to pick the most appropriate Rules Event for this rule to be triggered. But there are quite a few, straight forward, events you can pick from (depending on where exactly you want to use this field), just to mention a few:

Before inserting a new node (optionally limited to content type ABC). E.g. if your field is used to "Store the maximum speed on highways in country X".
Before saving an update to a user profile. E.g. if your field is used to "Store the duration (in days, months or years) of some type of membership subscription".

And your Rules Action is probably just a simple "Drupal set message". Though I can think of honeypot-scenarios where some specific values that got selected could result in a rules action like "block this user".

If you want even more granularity, you might also want to have a look at Conditional Rules, which allows for using "Rules Conditions" within "Rules Actions". Refer to my answer to "How to prevent a node being saved when using the Rules module?" for an illustration of using this module.


How to get referenced fields of a particular node/content type? I have a content type with reference field of type paragraph.

Using below code only gives me fields of content type and does not give referenced fields. How can I get referenced fields of a particular node type?

function hook_form_alter(array &$form, FormStateInterface &$form_state, $form_id) {
    $entityManager = \Drupal::service('entity.manager');
    $fields = $entityManager->getFieldDefinitions('node','media');
}

Once you have a $node object, you can get the referenced field value by the following code:

$node->get('field_reference')->referencedEntities();

Here, field_reference is a field of type Entity reference revisions referencing to the paragraph entity.


Alternative to Node Class module? I'm looking for a simple way to add classes to nodes. I found this module http://drupal.org/project/node_class but it is Minimally maintained.

Just wondering if is there any alternative to this module.

Check Skinr module.

If you are only looking for a straightforward way to add classes to nodes, you could do that even without any additional module.

Create a field called "css_class"
Hide that field from output
Edit the node.tpl.php file and print the value in the wrapper element

That should do the trick.


Change 'Log in', 'Log out', 'My account' menu text Is there a way that the default text in the account menu can be changed within the theme?

I needed to do the same but for a lot of items so working with the menu--account.html.twig was more confortable for me.

You can pick up string variable by using getUntranslatedString() method :

{% if item.title.getUntranslatedString() == 'Log in' %}
  <li{{ item.attributes.addClass(item_classes) }}>
  {{ link("new login text", item.url) }}

And if you want to do it for multiple strings :

{% if item.title.getUntranslatedString() == 'Log in' %}
 <li{{ item.attributes.addClass(item_classes) }}>
 {{ link('New login text', item.url) }}
{% elseif item.title.getUntranslatedString() == 'My account' %}
 <li{{ item.attributes.addClass(item_classes) }}>
 {{ link('new my account' text, item.url) }}
{% elseif item.title.getUntranslatedString() == 'Log out' %}
 <li{{ item.attributes.addClass(item_classes) }}>
 {{ link('new log out' text, item.url) }}
{% else %} {# when there is no match with the previous conditions #}
  <li{{ item.attributes.addClass(item_classes) }}>
  {{ link(item.title, item.url) }}
{% endif %}

Be sure to put your conditions before the trailing </li>


How do I use an HTML5 element for my field widget? I have found lots of resources about using HTML5 elements in custom forms (via Form API or using elements module). What's the standard technique which implements HTML5 field widgets (e.g. for a node field)?

For example, I have an "integer" field on node type "article" for which i want to use an HTML5 "number" input type. The only widget available to Fields API for data type number_integer is "textfield".

Your question is not clear please explain what HTML5 element you want to add to the form field. If you want to add placeholder or any other element you can pass them in #attributes, like this:

$form['name'] = array(
  '#type' => 'textfield',
  '#title' => t('First Name'),
  '#attributes' => array('placeholder' => 'First Name'),
);


I need to control access to a Views-generated JSON feed with OAuth (Drupal 6) I'm looking for a way to control access to a Views-generated JSON feed via OAuth, so individual users from a partner site can authorize access to certain of their profile data for use by the partner.

At this point, it seems clear that I need to use the services module with its attendant OAuth authentication to create a server that can hand over JSON. Is there some way I can use views to drive a server?

Is there a better way to approach this?

With the services and services_views modules, it's possible to repurpose any view into a service with OAuth authentication.

From my testbed, here's what the URL for the service looks like:

http://services.localhost:8082/sample_endpoint/views/tracker.json

where "sample_endpoint" is the name of the endpoint, "tracker" is the name of the view being provided as a service, and ".json" is the format for the returned content.


How to prevent users editing their profile, but allow password change? I have a Drupal 7 site that has additional fields added to the user profile page, to capture additional information (with these fields then displayed on the public-facing profile).

Only administrators should be able to edit non-admin profiles.

However, I am using !login_url (one time login) functionality in email confirmations to allow new users to set their own password and I need to retain this feature.

I have installed the User Protect module, but unless I enable the 'Edit own user account' permission, the one time login link returns a 'You are not authorized to access this page' message and the password cannot be entered.

Is there a way via User Protect, another module, or via custom code for me to retain the Change Password option, but remove access to all other fields that have been added to build a more complete profile?

You might be able to use the module: Password Hustle

  Adds the password set form as an optional fields on the one click
  login. In other words, we encourage (hustle) the user into setting
  their password as they log into the site via a one click login.


When to use a new field on the user account or a custom table and when use user.data service? Is there any rule when to use a new field in the user account for storing information and when to use the user.data service?

My initial approach was:
When the information should be editable either by an administrator or by the user itself, then use a new field. When the information should not be editable, only by code, use user.data service or a custom table.

E.g. in my case I am storing some information about where the user came from (marketing campaign) and some other information gathered during registration. This information is not meant to be shown to the user or edit by the user. Thus I decided to use the user.data service.

Now I am experiencing a very fast growth of the user_data table and I'm wondering whether my approach was correct. Maybe I should have created a new table for this or use a new field in the account.

Is there any rule when to use the user.data service and any limitations?

The purpose of the UserData API is to allow the storage of certain pieces of information related to a particular user. Its concept is similar to the State API in that the type of information stored is not a configuration that should be exported. In other words, it is specific to the current environment (but belonging to a given user rather than a system or
subsystem).

Users are content entities, who can have fields of various data types. These fields are typically used for structured information pertaining to the user, for example, a first and a last name. However, if you need to store something more irregular, such as user preferences or flag that a given user has done something, the UserData is a good place to do that. This is because the information is either not something structured or is not meant for the users themselves to manage.

In the other hand if you want to be able to export and import your user information in different environments then you should use fields.


Does it make sense to set a constant like THEME_IMAGE_DIR? Doesn't it make sense to assemble the theme's image path once, in a constant (eg THEME_IMAGE_DIR) and use this throughout the theme? This seems like too obvious, maybe I'm missing something...

Where would the ideal place for this initialization be? Module, theme, dark side of the moon? Inspired by Clive's answer

Declaration:

global $base_path;
$theme_path = drupal_get_path('theme', 'my_theme_name');
define('THEME_IMAGE_DIR', $base_path . $theme_path . '/images');

Usage:

$content['something'] = '<img src="' . THEME_IMAGE_DIR . '/inner-book.gif" />';

Dark side of the moon. Definitely ;)

Seriously though...any file that's included in every page load should be fair game to put this in. Personally I'd put it in a .module file so it's included before the theme level is even considered, but if you're only using it at the theme level then your theme's template.php file would be fine too.

As for whether or not it makes sense...if you find yourself repeating code of any kind then it makes sense to implement a constant/global/function to wrap around it. As the value in your particular case will not change in a single page load, a constant makes perfect sense to me.


Why can't I update my Drupal modules and themes? Suddenly I found my self in a big issue: I just can't upadate my Drupal modules and themes.

When I run the update script via the GUI, the download phase passes correctley (or it seems to be). But when I perform the database update and I click to "Continue" and putting the site under maintennace mode, nothing happens. And also a major problem come: the maintenance mode persist even when I disable it.

To resolve that issue I clear all the cache from the database.

Any idea or help for that?

1) try to run the updates via drush

2)are you sure that the new module version has a new hook_update_N in it? If not then there will be nothing happening during the update in GUI


Drupal address showing subfolder aswell I am having my site on www.abc.com which is hosted with hostgator. It is installed in public_html, and I installed Drupal in a sub-folder.

Whenever I go to my site, the address bar of the browser shows www.abc.com/techspot, when I would like it to show just www.abc.com.

How can I achieve this?

In your htaccess file you can set the rewrite rule:

# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
# RewriteBase /site


Translating taxonomy list name for a custom link in rewrite result field Very hard to describe this problem in a title. Let me explain:

I have a taxonomy list named 'Meubelen'. I translated the name to 'Meubles' for the French version of the website.

I created a view of the terms in this list (an overview of categories). An image of a representative node is shown for each term. I like te rewrite the output of this image to a link directing to the taxonomy page. I can do this for one language, like this:

 meubelen/[term-name]

But this should change to

 meubles/[term-name]

when visiting the French side of the website.

How can I achieve this? There's no translatable field for this view that I can add and use as variable.

How can I achieve this? There's no translatable field for this view that I can add and use as variable.

Really?!? If you have a representative node of the category content (with the proper language set) you should be able to have a relationship to that nodes language settings, and also the url path to nodes' url path for say, French, in this case.

There's no token support to Rewrite the link in Views to the path with X language setting for the node? .... eg, under Replacement Tokens for the field there's no configurable token for like, node:path:lang:YOUR-LANG or something similar -- I typically dont do internation sites, but i'm 99% sure this type of flexability comes out of the box.


Bulk Delete Custom Entities (Not Entity Types) I have a 5000+ entries for custom Entities created by the RedHen module (https://drupal.org/project/redhen). I want to wipe them completely from the system (they are all test entries). How can I do this quickly? I tried to get Views Bulk Operations and the Delete All modules but neither seem to be picking up the custom entities.

You can  delete multiple entities using below API functions

entity_load

  Load entities from the database.

  The entities are stored in a static memory cache, and will not require
  database access if loaded again during the same page request.

  $entity_type: The entity type to load, e.g. node or user.

  $ids: An array of entity IDs, or FALSE to load all entities.

entity_delete_multiple

  Permanently delete multiple entities.

For Example to delete all node entities

<?php
  $results = entity_load('node');
  $entity_ids = array_keys($results);
  entity_delete_multiple('node', $entity_ids);
  ?>


Why wouldn't hook_form_submit be called? function mymodule_reviewer_node_form($node, &$form_state) {
global $school;
if ($school) {
    $form['field_reviewer_school']['#value'] = array(array('nid' => $school));
    $form['field_reviewer_school']['#access'] = FALSE;
}
  return $form;
}

function mymodule_reviewer_node_form_submit($node, &$form_state) {
}

The form gets submitted successfully, but form_submit never gets called. What might cause this?

The form should be:

   function  mymod_reviewer_node_form($form_state) {
     $form = array();

     // Build the form...

     return $form;
   }

The submit handler should be:

   function mymod_reviewer_node_form_submit($form, &$form_state) {
     // Do something with $form_state['values'] or whatever
   }

And make sure that whatever is rendering the form passes through drupal_get_form().

Finally, one tricky bit: Make sure you are not accidentally overriding a hook. mymod_form(), for example, implements hook_form(), which is probably not what you really intend to do.

I find that nine times out of ten, if the submit handler is not being called, it's because I named the function incorrectly.


How to let an OG administrator contact (via email) all group members? I've a request to set up an email form where by a OG administrator can send a message (via email) to all persons subscribed to that group.

I've seen a few modules OG Contact, OG Notify, and Organic Groups Email, but these seem out of date.

This question have been answer at -  How to loop over a list of Organic Group users using Rules

and at - How to send an email to Drupal 7 Organic Groups Role Members? in here is going to show you how to do it with a custom module.

There other alternatives:

1- You can use views_bulk_operations

  I would think you should be able to do it by adding views_bulk_operations to the mix-- that should give you the ability to email users in a view which you can setup with the criteria you need via filtering.

Source

2- You can do it with Rules

  Looping over a list can only be done in Rules (i.e. for Drupal 7).

Source


why i can't update user's picture by user_save() i wrote the program belowed

$fields=array('name'=>'test user','picture'=>$fid);

$account=user_save($account, $fields);

i really changed the user name but i can't change the picture field in the users table

what could the problem be?

by the way, i also use db_update. The situation is the same

the code is blowed

db_update('users')
->condition('uid',$account->uid)
->fields(array('picture'=>$file->fid))
->execute();

still not work
I hope somebody can help me,Thanks!

Try this code

 $file = file_load($fid);
 $file->status = 0;
 $edit = array ('picture' => $file);
 $u = user_save($account,$edit);


Is there a way to set the pager's page number programmatically without the page being in the url? I would like a user who has previously left a comment on a node to initially see the last page of comments while a new user (to that node) will initially see the first page of comments.
I know that the page is controlled by the pager and is set by the "page" variable in the URL ($_GET['page']). Is there a way to set this programmatically?

(Just to clarify, I am not using the Views module on this project.)

You can use AJAX to call a new request so you will not have the page in the URL
or, if you use Views, select "Use AJAX" under the Advanced Settings, and it will enable AJAX on your pager.


Add a text field to OG subscription form I would like to add a text field to the og_ui_confirm_subscribe form so that applicants can motivate their request to the owner of the group.

I don't have any problem to create the field and attach it to this form through a simple hook_form_alter but I am lost once I have to link the text field to the user of the OG admin...

I've googled but it doesn't seem to be a highly requested feature (only a - brief - mention found in OG 4.7 but this didn't led any further. It's weird since it means that admin are supposed to accept/deny only based on username...

By the way, these OG admin pages are very poor in terms of UI so I might think customizing them with Views & VBO; would this direction be a good way to go to easily get my text field?

I noticed it is possible to add this field (and others if needed) through the OG settings of the membership (cf. admin/config/group/group-membership/manage/NAME_OF_YOUR_OG_MEMBERSHIP/fields).


Group users and display the group on the profile page How can I create a group/role/taxonomy term or anything else to group specific users ? I also want to display the "group/role/taxonomy term or anything else" on the users profile.

For example: I go to example.com/user/1 and I see all of his details AND that he has the administrator-"group/role/taxonomy term or anything else".

Thanks in advance (I am a noob here)

Roles have a set of permissions, so they are ideal if you will have a set of users  editing certain types of content,
 like blog posts, and another group of user commenting on the content.
 You can create both new roles and permissions.

Roles: /admin/people/roles
Permissions: /admin/people/permissions

You can also add fields to the users, like a taxonomy where they choose whether they are a dog person or a cat person.

Manage fields: /admin/config/people/accounts/fields
Manage form display: /admin/config/people/accounts/form-display

Then, you can choose which fields will be displayed on the user profile page

Manage display: /admin/config/people/accounts/display


How do I change the transport for remote drush alias calls We're moving to an environment where our drupal instances will live inside docker containers managed by kubernetes.

Currently I've got scripts for things like checking module security status across large numbers of drupal sites.  Basically I maintain a file full of aliases, and I iterate over those.  It works well enough.

With the move to kubernetes, what I'd like to happen is that my aliases would somehow specify that the way to call the remote instance is via a kubectl command that effectively invokes drush in the remote container.  It looks a lot like an alternative to ssh as the transport.

Is something like this possible?
OK, so I've got the source code, and anything is presumably possible, but what might a sensible approach look like?  What should I look at to get my head around this?

It seems that you currently can't change the transport / replace SSH. However, most of the work can be fixed be writing wrapper scripts. Read https://github.com/drush-ops/drush/issues/2367


Drupal cross server workflow I have my test server installed locally with MAMP and so far everything is going fine but one concern I am having is how will I deploy my server remotely once I want to have a live server.  Is there an easy workflow to export all your content, fields and views so that I can move them to a remote server using ftp maybe?  How does this type of workflow normally work?

Here are some links to some articles which might be helpful. I've been compiling them myself, to help figure out how to tackle the same issue you're having.

Exploring Deployment Methods

http://torylawson.com/index.php?title=Moving_Drupal_7_site_to_a_new_server
How to migrate from test environment to production environment?
Creating a Drupal development environment - achieving development, stage and production: http://groups.drupal.org/node/24196
http://developmentseed.org/blog/2009/jul/09/development-staging-production-workflow-problem-drupal/
http://www.slideshare.net/eaton/drupal-deployment-presentation

Moving Configuration out of the Database with Features

Bundling site settings using Features - http://drupal.org/node/580026
http://developmentseed.org/blog/2009/may/29/making-and-using-features-drupal/

Using Git with Drupal (http://github.com)

Drupal Git Tutorials List - http://drupal.org/node/1054594
Building a Drupal site with Git - http://drupal.org/node/803746
Drupal + Git database management - http://patrickavella.com/blog/git-drupal
https://stackoverflow.com/questions/5364498/drupal-on-git-what-to-do-with-the-database
http://www.opc.com.au/web-development/drupal-release-management-drush-and-git
http://www.viget.com/extend/backup-your-database-in-git/

Useful Contrib Modules

http://drupal.org/project/backup_migrate
http://drupal.org/project/features
http://drupal.org/project/drush


Unable to Edit  in Product Pages I am unable to edit the  tag on any of my product pages, however, I am able to edit on all other pages. The Page Title option or slot is not even shown on the edit of my products. I have the Page Title module (6.x-2.5) uploaded and enabled. Any ideas?

Page Title is enabled (or disabled) on a per content-type basis.

You should be able to go to http://mysite.com/admin/content/types/product and enable it using the checkbox in the following fieldset:


What cache tables should I keep on Memcache on a multi-site server? I can spare 64-96Mb of memory on my VPS running a dozen Drupal 6 and 7 sites. In this situation, what cache tables should I keep on Memcache, and why?

I realize cache_update and cache_form are not proper caches, but my question rather assumes it's better to have a few well-cached tables than lots of poorly cached ones. Is this assumption correct?

I guess the question is if and when those tables would be "poorly cached". This will depend completely on the actual request load of your website. Without detailed insight it's hard to give you a concrete recommendation, except that "premature optimization is the root of all evil" (D. Knuth).

Therefore, simply start with caching all tables in Memcache and then measure how effective (hits vs. misses) Memcache works. You could do this with the Memcache admin module or, with a bit more effort, using Munin. Then you'll see if you actually should shift some RAM from the more ineffective tables to the more frequented ones. That's exactly what we do to optimize Memcache on our Drupal hosting clusters.


Randomly show one item from the last x posted I have worked out how to select a random item - add a sort criteria of type Global: Random. I can also select from, say, the last month, by adding a filter. However, if I want to select randomly from the last, say, 5 items posted, I can't find a way to do that.

Sort your View by Content: Post date (desc) and set the Pager to Use pager: Display a specified number of items | 5 items

Go to the Advanced Settings in the view and click in the Theme: Information

Search the Style output: section and select a name, in my case was views-view-unformatted--temp.tpl.php

Go to the folder YOUR_SITE/sites/all/modules/views/theme and copy to your theme folder the file views-view-unformatted.tpl.php and rename it to views-view-unformatted--temp.tpl.php

Edit your new file views-view-unformatted--temp.tpl.php and put inside only this code to show only one element:

<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
 //Selecting one element from your last 5 posted elements
 $element = $rows[rand(0, 4)];
 $rows = array();
 $rows[] = $element;

?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>

In the View go to the bottom of the Information window and click Rescan template files and click OK, then save your View.

And go to see your result.

Attention: Remember to repeat these steps if you ever change theme.


How to render a taxonomy field in a Views' PHP code field? In Views PHP code, I could render a field by :-

<?php
  print drupal_render($data->field_field_my_text);
?>

But this only seems to work field with type Text. I have a field which is Taxonomy (Term Reference) and I am trying to output that through the above code but it's not working.

This is what I wrote:-

<?php
      print drupal_render($data->field_field_my_category);
    ?>

Unfortunately, this is not working. Any idea what I should do here?

Thanks.

I can't comment because of rep..
Use devel module and use the dpm() function in your php for some debugging, drill down and find the value you are looking for then double click the value in the debug widget and it should tell you your field value.

here's my guess:

$data->field_field_my_category[0]['raw']['value'];

Might be slightly different if it's a tax term but devel is your best friend and you should use it quite frequently. Stop guessing and start debuging (best advice i've ever gotten).


Entity reference with ddf, dynamic dependent fields I'm not able to configure ddf module, I followed the instructions but still nothing.

I'm sure is the best module for my necessity.

I have a content type "house" with a field "rooms" with cardinality +1.

In another content type I have a field "house", an entity reference of the "house" c. type and a dependent select list of rooms that should be updated by the value chosen on the precedent field.

I installed the ddf module, I created the view with the contextual filter and configured the dependent value with dynamic argument.

Unfortunately I'm missing something and the dependent value doesn't reload with the correct values.

Any tip will be much appreciated !

DDF is a complex-looking module but there are only a few areas where you might make a mistake.  Try enabling the submodule "DDF Entity Reference" on the modules page if you have not done so already.  If you are still having problems after enabling the submodule, post here and I'll take another look at your entity reference view setup.


Using form_set_error in the submit handler I have a multistep form and on each submit I send completed fields off to an external API which returns data about the next step of the form.

The problem is, if I use form_set_error in the submit handler, the form_storage is cleared and so the form resets to the first page.

Here's a arbitrary example;

function example_form($form, &$form_state) {
  if(!isset($form_state['step'])){
    $form_state['step'] = 1;
  }
  $form['test'] = array('#markup' => '
Step: ' . $form_state['step'] . '
');

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'go'
  );
  return $form;
}

function example_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
  if($form_state['step'] > 5){
    form_set_error('test', 'error');
    return;
  }
  $form_state['step']++;
}

So this create a form with just a text block displaying the step number and a submit button that takes you to the next step. Until you go past the 5th step at which point it should start to error.

For some reason in my testing this breaks the step count, and on error takes you back to step 2.

moving the form_set_error into the form callback, or into a validate callback fixes the issue, but it would be cleaner if I could call it in the submit handler.

In case it's useful to anyone else, I have a unsatisfactory work around;

Store the error in form_state, and look for them in the form callback.

function example_form($form, &$form_state) {
  // if we had an error in the submit handler, trigger it now
  if(isset($form_state['error']) && $form_state['error']){
    form_set_error('test', 'test');
  }
  if(!isset($form_state['step'])){
    $form_state['step'] = 1;
  }
  $form['test'] = array('#markup' => '
Step: ' . $form_state['step'] . '
');

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'go'
  );
  return $form;
}

function example_submit($form, &$form_state) {

  $form_state['rebuild'] = TRUE;
  if($form_state['step'] > 5){
    //store error and return before the step is increased
    $form_state['error'] = true;
    return;
  }

  $form_state['step']++;
}


Place a block in multiple regions Is there a module which can allow users to place the same block in multiple regions? That way I don't have to make the same View block twice.

Multiblock module makes this possible:

  Drupal's block module is limited by the fact that a block can only
  have one instance. Each block has a 1:1 relationship with its region,
  weight, visibility (and other) settings. This means that it is
  impossible to have blocks in multiple regions or to have blocks that
  have different settings on different pages. MultiBlock module solves
  this problem by allowing you to create multiple Block Instances of
  already existing blocks.


user_presave doesn't work correctly when new account is created My users have 2 fields: 'A' and 'B'. The value of the second one depends on the value of the first one and is set by the following custom module:

function MYMODULE_user_presave (&$edit, $account) {
    $tid = $edit['field_A']['und'][0]['target_id'];
    if (isset ($account->roles[3])) {
        $B = taxonomy_term_load(8);
        }
        else {
            $B = taxonomy_term_load($tid);
        }
    $edit['field_B']['und'][0]['fid'] = $B->field_B['und'][0]['fid'];
}

It works fine, but when an anonymous user registrates himself/herself, it fails: the if is evaluated as true and the new user gets the wrong value in 'B'. When I commented out the if and only left over the else action, it did work, so it has something to do with the $account.

What's going wrong and how can I solve this?

Note: role 3 is the built-in administrator role.

Edit: This is my final code after @m1n0's answer:

function MYHOOK_user_presave (&$edit, $account) {
    $tid = $edit['field_A']['und'][0]['target_id'];
    if ($account->is_new OR !isset ($account->roles[3])) {
        $B = taxonomy_term_load($tid);
        }
        else {
            $B = taxonomy_term_load(8);
        }
    $edit['field_B']['und'][0]['fid'] = $B->field_B['und'][0]['fid'];
}

As stated in the documentation (https://api.drupal.org/api/drupal/modules%21user%21user.api.php/function/hook_user_presave/7), you need to check whether the user is being created or not with the following code:

if ($account->is_new)

The reason is that $edit contains the values submitted, and $account contains the existing user data - but on user registration, there is no user that already exists in the database.
Your code should check whether new user is being created and in that case assign some default value (like you already have with $B= taxonomy_term_load($tid);)


Drupal user one off settings I am putting together a complex Drupal user driven website. One thing I need to accomplish early on is to put users into groups as they register.

Can anyone tell me how I can get them to register particular details which they will not be able to amend in the future? Such data as the users gender etc....?

Thanks.

For the user groups, use the auto assign role module and you could use content profile and CCK to create profile fields that the user can fill in.  You could use the content permissions module that's a part of CCK to allow a user to create a profile but not to edit certain fields once they've been created.


Can "Demonstrate block regions" use a specific template? I have two templates in my theme called page--front.tpl.php and page.tpl.php. When I click at the link "Demonstrate block regions" (Structure/Block) it shows the page.tpl.php template. Is it possibly to change the template to page--front.tpl.php?

Thank you for your answer.

My .info file look like this
name = xxx
description = xxxxx
core = 7.x
engine = phptemplate
stylesheets[all][] = css/css.css
regions[banner] = Banner
regions[header] = Header
regions[leftcolumn] = Left Column
regions[content] = Content Column
regions[rightcolumn] = Right Column
regions[footer] = Footer

It should be all right I think?

page.tpl.php is my sub page and consist of the regions: banner, header, left column, content column and footer.
page--front.tpl.php is my front page and consist of the regions: banner, header, left column, content column, right column and footer.

The website works perfectly. It shows content as it should do. But when I use the link "Demonstrate block regions" (Structure/Block) it shows the page.tpl.php template (I have checked that with devel_themer). I can see the regions: banner, header, left column, content column and footer. Not the region right column.

I wish it was the template page--front.tpl.php instead of  page.tpl.php so I could see all the regions.

In order for a region to show up on the demonstration block, you need to define it in your theme's .info file and print the region in page.tpl.php (or the overrided version). The following could be the issue

Cache is not cleared (i.e. drush cc theme-registry if you are using drush)
Theme's .info file has not listed the new region
Page template is not overrided properly
The region is not printed properly in .tpl.php file

I would say, have a look into guide on how to override a template file prpperly here https://www.drupal.org/node/1089656 and https://www.drupal.org/node/223440#custom-suggestions.

If you would like a region to NOT show up on the front page, you can simply do not supply content to it and Drupal will not render it.

If you would like to add an extra region, then google for some tutorials on how to create custom regions.

Install Devel related modules.

devel_themer module, make it very easy to do themeing in Drupal, specially if you are new.

If you have devel_themer installed and enabled, then you can click on the page and see which template file is being used to render the page. You can click on regions, blocks and elements and it will give you details on how it is rendered and which template/function being used.

Hope this general answer help you.


Custom validate and submit don't works I made my custom module, and wanted to do some staff in the validation and submission handlers. My Fields are in two field sets:

Member profile, with username and password
Company profile, with company name, URL, location, and logo

I am also using the #states attribute on some fields, but everything works except the validation and submission handlers.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_profile_form':
      // Only pre-render works.
      $form['#pre_render'][] = 'mymodule_user_profile_form_pre_render';
      // I try to empty fields with states attribute, but without success. Disabled work OK.
      $form['field_company_url']['und']['0']['value']['#states'] = array(
       'empty' => array(':input[name="field_company_confidential[und]"]' => array('checked' => TRUE)),
       'disabled' => array(':input[name="field_company_confidential[und]"]' => array('checked' => TRUE)),);

      // These don't work as expected.
      $form['#validate'][] = 'mymodule_user_profile_form_validate';
      $form['#submit'][] = 'mymodule_user_profile_form_submit';

      // I also tried this one.
      // $form['actions']['submit']['#submit'][] = 'mymodule_user_profile_form_submit';
  }
}

function mymodule_user_profile_form_submit($form, &$form_state) {
  // I want to download the image from another website and set as logo.
}

function mymodule_user_profile_form_validate($form, &$form_state) {
  //I need to check if checkbox is checked to empty all other fields.
  if ($form_state['values']['field_company_confidential'] == TRUE) {
    $form_state['values']['field_company_url']['und']['0'] = '';
  }

  return $form;
}

When I try to access $form_state['values'], I don't get any value.

What I am doing wrong?

The main problem was with devel module.
When I disable it and try again all job everything works perfect.
So maybe was some bugs with devel module, but I am not sure.


User flagged nodes in views I'm using the flag module with Views.  I need to display all the nodes a user has flagged. This is quite similar (point.3) View of users flagged by a user, users flagging a user, and nodes from users flagged by a user - But there doesn't appear to be an answer. Any idea how to achieve this?

The view will take in the uid as a contextual filter from the URL.  But I'm not sure how to print out the related flagged content, as the view has only user information available..

Edit> There will be multiple users in which anyone can view the profiles of. On a users profile there is a tab called 'Following'.  This needs to show the nodes that the user (being viewed) has flagged 'follow'.  So I've created a page in a view 'user/%/following' for example.. I've included the flag relationship, I just need to print out the node teasers.. This option doesn't appear to be available..

Any ideas? Cheers!

I'm not sure I understood the question... it is very simple.
You don't need contextual filter, you need to add a relationship with Flag by current user.
Click on relationship a look for Flags: User's flagged content, then select the type of flag and here we go, you got a page or a block with the content flagged by the current user.

If you are using drupal 7 import this view to see if it's what you are looking for

$view = new view;
$view->name = 'User Follow';
$view->description = '';
$view->tag = 'flag';
$view->base_table = 'node';
$view->human_name = '';
$view->core = 0;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['title'] = 'User bookmarks';
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  2 => '2',
);
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'type' => 'type',
  'title' => 'title',
  'name' => 'name',
  'comment_count' => 'comment_count',
  'last_comment_timestamp' => 'last_comment_timestamp',
);
$handler->display->display_options['style_options']['default'] = 'last_comment_timestamp';
$handler->display->display_options['style_options']['info'] = array(
  'type' => array(
    'sortable' => TRUE,
  ),
  'title' => array(
    'sortable' => TRUE,
  ),
  'name' => array(
    'sortable' => TRUE,
  ),
  'comment_count' => array(
    'sortable' => TRUE,
  ),
  'last_comment_timestamp' => array(
    'sortable' => TRUE,
  ),
);
$handler->display->display_options['style_options']['override'] = FALSE;
$handler->display->display_options['style_options']['sticky'] = 1;
$handler->display->display_options['style_options']['order'] = 'desc';
/* No results behavior: Global: Text area */
$handler->display->display_options['empty']['text']['id'] = 'area';
$handler->display->display_options['empty']['text']['table'] = 'views';
$handler->display->display_options['empty']['text']['field'] = 'area';
$handler->display->display_options['empty']['text']['empty'] = FALSE;
$handler->display->display_options['empty']['text']['content'] = 'This user has not yet bookmarked any content.';
$handler->display->display_options['empty']['text']['format'] = 'plain_text';
/* Relationship: Flags: bookmarks */
$handler->display->display_options['relationships']['flag_content_rel']['id'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['table'] = 'node';
$handler->display->display_options['relationships']['flag_content_rel']['field'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['label'] = 'bookmarks';
$handler->display->display_options['relationships']['flag_content_rel']['flag'] = 'bookmarks';
$handler->display->display_options['relationships']['flag_content_rel']['user_scope'] = 'any';
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid_1']['id'] = 'uid_1';
$handler->display->display_options['relationships']['uid_1']['table'] = 'node';
$handler->display->display_options['relationships']['uid_1']['field'] = 'uid';
$handler->display->display_options['relationships']['uid_1']['required'] = 0;
/* Relationship: Flags: User */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'flag_content';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['relationship'] = 'flag_content_rel';
$handler->display->display_options['relationships']['uid']['label'] = 'bookmarks_user';
$handler->display->display_options['relationships']['uid']['required'] = 1;
/* Field: Content: Type */
$handler->display->display_options['fields']['type']['id'] = 'type';
$handler->display->display_options['fields']['type']['table'] = 'node';
$handler->display->display_options['fields']['type']['field'] = 'type';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['link_to_node'] = 1;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid_1';
$handler->display->display_options['fields']['name']['label'] = 'Author';
$handler->display->display_options['fields']['name']['link_to_user'] = 1;
/* Field: Content: Comment count */
$handler->display->display_options['fields']['comment_count']['id'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['table'] = 'node_comment_statistics';
$handler->display->display_options['fields']['comment_count']['field'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['label'] = 'Replies';
/* Field: Content: Last comment time */
$handler->display->display_options['fields']['last_comment_timestamp']['id'] = 'last_comment_timestamp';
$handler->display->display_options['fields']['last_comment_timestamp']['table'] = 'node_comment_statistics';
$handler->display->display_options['fields']['last_comment_timestamp']['field'] = 'last_comment_timestamp';
$handler->display->display_options['fields']['last_comment_timestamp']['label'] = 'Last Post';
/* Contextual filter: User: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'users';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['relationship'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'empty';
$handler->display->display_options['arguments']['uid']['exception']['title_enable'] = 1;
$handler->display->display_options['arguments']['uid']['title_enable'] = 1;
$handler->display->display_options['arguments']['uid']['title'] = '%1\'s bookmarks';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['specify_validation'] = 1;
$handler->display->display_options['arguments']['uid']['break_phrase'] = 0;
$handler->display->display_options['arguments']['uid']['not'] = 0;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'user/%/bookmarks';
$handler->display->display_options['menu']['title'] = 'Bookmarks';
$handler->display->display_options['menu']['weight'] = '0';


Drupal Front end Form with fields with option to add More Fields I want to create a Form in the frontend, so user can able to add the data in the form and submit the data. Then i have to display all the data submitted by the user using that form. Just like a Internal Messaging system. I want a Add Reports Form and i want to list all the reports in a page ( View Reports). I planned to create a content type ( Reports), After that i will be able to add the fields. Upto this i know how to do. But i want to know how to have a row with three fields with add button, then if user click on the button,  i want to append a new row with same three fields. Just like Multiple Image upload. I have screenshot. In screen one, i have a add button above a row with three fields. In the screen two which is taken after clicking the "add button" , It displays the same add button with two rows with same three fields .

Screen 1 :

Screen 2 :

Any help would be greatly appreciated.

Assuming that "Name of Stocklists", "Sales as on Date", and "Closing Stock Value" are all CCK fields, you should be able to do this using Field Collection (https://drupal.org/project/field_collection).

1) Install Field Collection

2) Create a field collection field on your Report content type. Use the embedded widget. Be sure to make the field multi-value / unlimited values.

3) Go to admin/structure/field-collections and click Manage Fields for the field collection you created.

4) Add the 3 stock text fields to the field collection.

5) Now on the Report add/edit forms, you'll have the "Add Another Item" button.

To align the fields in a row, you should be able to use CSS. To make the button a +, you should be able to use hook_form_alter() or hook_form_report_node_form_alter().


Where and how to conditionally redirect old aliases to new aliases We are replacing a website with a new version. The domain is the same, but URL aliases in the new website are different.

In many cases, I can use an old alias to calculate its corresponding new alias. There are many thousands of old aliases, so I don't want to just use the Redirect module. I know how to write the calculations and how to check if a calculated new alias exists.

I need to know at what point I can intercept each incoming URL to calculate a new alias.

I also need to know how to redirect to the calculated new alias if it exists.

Concrete example:

A book chapter on the old site is at example.com/recent/secrets-to-success/10-knowing-when-to-quit. This chapter on the new site is at example.com/secrets-to-success/knowing-when-quit. The difference is (a) we no longer add the recent subfolder, (b) we've removed chapter numbers from chapter titles, and (c) we've changed which words are ignored when an alias is auto-generated.

When someone uses an old alias, I want to intercept it, calculate the new alias, check if it exists, and redirect to it if it does. This is only one example. There are several other ways of calculating, so there's some trial and error involved. But I know how to take care of that.

This solution is based on a suggestion by @4k4 at Redirect from within controller always goes to home page.

My custom module is named rsc.

In modules/custom/rsc the file rsc.services.yml includes the following:

services:
  rsc.event.Redirect404:
    class: Drupal\rsc\EventSubscriber\rscRedirect404
    tags:
      - {name: event_subscriber}

In modules/custom/rsc/src/EventSubscriber the file rscRedirect404.php contains the following:

<?php
namespace Drupal\rsc\EventSubscriber;

use Drupal\Core\EventSubscriber\HttpExceptionSubscriberBase;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;

class rscRedirect404 extends HttpExceptionSubscriberBase {

  protected function getHandledFormats() { // required
    return ['html'];
  }

  public function on404(GetResponseForExceptionEvent $event) {

    $path = \Drupal::request()->getPathInfo();
    $path = [code to modify the path from old site to new site]

    if (($url = \Drupal::service('path.validator')->getUrlIfValid($path))) {
      $event->setResponse(new RedirectResponse(URL::fromUserInput($path)->toString()));
    }
  }
}

With this in place, I see 404 redirects before they get passed to the default handler. If I do the $event->setResponse(), the user is redirected as I specify. If not, normal processing occurs.

In reality, the line that says [code to modify the path from old site to new site] is multiple lines where I do several trial-and-error tests to figure out the correct new URL,  but everything else is just as I'm using it.


What is the difference between getValue() and referencedEntities() to fetch paragraphs? What is the difference between using getValue() and referencedEntities() in order to get the paragraph on a node?

See example below. Both examples are used in a node template such as node--page--full.html.twig and mymodule_preprocess_node() hook.

Using getValue()

$paragraph = $node->field_paragraph->getValue();
foreach ( $paragraph as $pr ) {
  // Get the entity using Paragraph::load(entity_id).
  $pr_item = \Drupal\paragraphs\Entity\Paragraph::load($pr['target_id']);

  // Now use $pr_item to get any field.
  $pr_item_img = $pr_item->field_image;
}

Using referencedEntities()

$pr_field = $node->field_paragraph->referencedEntities();
foreach($pr_field as $pr) {
  $item_image = $pr->get('field_image');
}

I am mainly concerned with the following:

What is more performant?
What is the best practice since both work?
Is either method considered a magic method? I ask because you can use $node->field_paragraph as opposed to $node->get('field_paragraph')

Performance

EntityReferenceFieldItemList::referencedEntities performs better because it uses loadMultiple() instead of loading the entities separately.

Best practice

You use static code to load the entity which should be avoided when possible. You could make proper OOP code out of it, but it is also best practice to not reinvent the wheel.

Edit:
You've added the info this is in node preprocess. Then best practice would be to render the paragraph field in the node template {{ content.field_paragraph }}. Configure the field in UI, for example add a custom view mode. Theme the output in field and paragraph templates for this specific field or view mode.

Magic method

No, this doesn't involve a magic method,  the method is called directly. A magic method is involved in getting entity fields as if they were object properties, like the example you've mentioned $node->field_paragraph.

Translation

You need to translate the entities for both methods before you can output translated field values directly:

$paragraph = \Drupal::service('entity.repository')
  ->getTranslationFromContext($paragraph, $langcode);

By the way core translates the entities later when building the rendered output using the entity reference field formatter. This works for core because it usually doesn't output field values directly, so this could be considered as bad practice as well, see for example this question from today How to display Paragraph bundles fields links inside a page.html.twig file that are within a paragraph bundle in Twig?.

Revisions

Paragraphs are stored in an EntityReferenceRevisions field. Your example code ignores the revision data and so you might load the wrong version. One more reason to use the methods provided by the field, referencedEntities() or $item->entity in case you need to load a single entity.


Exposed filters - block? Is it possible to create a block that allows users to sort the nodes in a view? I've only been able to achieve this in a page using the menu in page settings but so far haven't had any luck with blocks. The thing is I need the block to appear on most of the site's pages. Any ideas...?

All you need to do is set up the exposed filters and then click Exposed form in block in the Basic Settings. This will then give you a block to use.


Check URL for string in a Twig file I'm new to twig and drupal 8 and finding it hard to access page titles. I want to apply a class to a page title on certain pages, all of which share a sub-directory in the URL path. I'm working with a page-title.html.twig file and want to do something like this:

{{ title_prefix }}
{% if title %}
  {% if <url contains "/services/"> %}

{{ title }}

  {% else %}

{{ title }}

  {% endif %}
{% endif %}
{{ title_suffix }}

I'm assuming this is possible, I just can't figure out how to check the URL for the desired string.

Use the "in" operator:

{% if '/services/' in url %}

More information: http://twig.sensiolabs.org/doc/templates.html#containment-operator

If you didn't do it already, put this preprocess function in the file mytheme.theme in your theme directory:

function mytheme_preprocess_page_title(&$variables) {
  $variables['url'] = $_SERVER['REQUEST_URI'];
  $variables['#cache']['contexts'][] = 'url.path';
}

Edit:
By moving the code from page inside a block we need to provide a cache context.


EntityFieldQuery in a loop i'm using EntityFieldQuery to retrieve some nodes according to some conditions.

foreach (array("important", "normal") as $type) {
  $query = new EntityFieldQuery();
  $query->entityCondition("entity_type", "node")
    ->entityCondition("bundle", "Announce")
    ->fieldCondition("field_ann_cat", "value", array($nid))
    ->fieldCondition("field_ann_type", "value", array($type));
  $result = $query->execute();
  var_dump($result);
  // Some actions
}

The first time it loops, i have my announces marked as "important" (field_ann_type).
The second time it loops, i dont have any announces marked as "normal".

I've tried to intervert them, and when i have array("normal", "important") instead of array("important", "normal") in my foreach, i can see my announces marked as "normal", but not my announces marked as "important".

Does anyone knows why?
Thanks.

It may be because you are doing this:

->fieldCondition("field_ann_type", "value", array($type));

try just check it against $type like this:

->fieldCondition("field_ann_type", "value", $type);


Exposed Filters Search : remove parameters from URL i need to create something like a landing page search block (using views exposed filters) that links to a new search page.  I have problems with my current set up and I am trying to avoid any code tweaks.

My current exposed block sends the results to a result page.  However, the parameters are passed in the URL. instead of seeing
mysite.com/results  one sees mysite.com/results?taxonomy_vocabulary_3_tid=blue.  How can configure so that the user only sees the main url.

Also, My search box is not showing up on the results page. Is there a way to configure so that the results page allows you to submit another search. I would think that would be a pretty standard set up.

Thanks!

Looks like there is a module that changes the views arguments from a GET to a POST.

Views ExPost


Facet - default value with search api I am using content type in Facet. The search result will be having an option to choose the content type to filter the result.

I want the search should show the result with particular content-type filtered by default. Is it possible? If so, how to do that?

To be little more clear instead of

https://example.com/searchpage?search_terms=xxxx

I want to search as following by default.

https://example.com/searchpage?search_terms=xxxx&f[0]=content_type:content_page&f[1]=content_type:cotent_page

Not sure you can do this with facets.  Facets by definition show only options that exist in the current query results.  There is no guarantee that a content_page type will be among the search results for a term.

You may want to consider using an exposed view filter (the views_block_filter_block module lets you turn this into a place-able block).  This would show all content types and can have a default type selected if the filter has none.


How do I set a Boolean config variable to false? I can't set a boolean config value to FALSE with drush.  I'm using Drush 8.9.4.
pk@DC:~/$ lando drush config-set advagg.settings enabled 0 -y

 // Do you want to update enabled key in advagg.settings config?: yes.

pk@DC:~/$ lando drush config-get advagg.settings enabled
'advagg.settings:enabled': false

pk@DC:~/$ lando drush config-set advagg.settings enabled true -y

 // Do you want to update enabled key in advagg.settings config?: yes.

pk@DC:~/$ lando drush config-get advagg.settings enabled
'advagg.settings:enabled': true

pk@DC:~/$ lando drush config-set advagg.settings enabled false -y

 // Do you want to update enabled key in advagg.settings config?: yes.

pk@DC:~/$ lando drush config-get advagg.settings enabled
'advagg.settings:enabled': true

Why does setting it to false make it true?

When setting a boolean with drush, you need to use 0, not false.
pk@DC:~/$ lando drush config-get advagg.settings enabled
'advagg.settings:enabled': true

pk@DC:~/$ lando drush config-set advagg.settings enabled 0 -y

 // Do you want to update enabled key in advagg.settings config?: yes.

pk@DC:~/$ lando drush config-get advagg.settings enabled
'advagg.settings:enabled': false


IP-numbers not found in database table ip2country I am trying to hide a certain field in the product nodes for all visitors from other countries. I have installed the ip2country module and I am using this code snippet to fetch the language code in my module:

$ip = ip_address();
$country_code = get_country($ip);
dsm($ip . " " . $country_code);

The IP address is showing but not the country code. I am testing this on a web server and the IP printed by the dsm seems OK. I have also copied and renamed the ip2country_get_country($ip_address) function from the ip2 country module to experiment with different solutions in my own module:

function get_country($ip_address) {
  $ipl = ip2long($ip_address);
  if (is_long($ip_address)) {
    $ipl = $ip_address;
  }
dsm($ipl);
  // Locate IP within range.
  $sql    = "SELECT country FROM {ip2country}
             WHERE (:start >= ip_range_first AND :end <= ip_range_last) LIMIT 1";
  $result = db_query($sql, array(':start' => $ipl, ':end' => $ipl))->fetchField();

  return $result;
}

The thing is that the long ip produced by the get_country() function ($ipl = ip2long($ip_address)) is ten numbers, and as far as I can see in the database table no numbers for my country (Sweden) is made up of ten numbers... So it's not strange that the db query does not return the expected result ('SE'). There must be something obvious I am missing here... ? I have experimented with SQL queries directly in phpMyAdmin and I can confirm that the IP number is not to be found in any of the ranges given.

The comment from AyeshK led me to the right answer. I found this in the php manual:

  As pointed out by others, this function's return value is not
  consistent on 32 and 64-bit platforms.

  Your best bet for consistent behavior across 32/64-bit platforms (and
  Windows) is the lowest common denominator: force the return value of
  ip2long() into a signed 32-bit integer, e.g.:

var_dump(unpack('l', pack('l', ip2long('255.255.255.0'))));

And so I changed this row $ipl = ip2long($ip_address); into this $ipl = unpack('l', pack('l', ip2long($ip_address))); and now it works!

But if there is a better solution, please let me know.


How do I fund a project? I'm just trying to find out how to fund a Drupal project.

I found https://www.drupalfund.us/, but it seems it is not really working because there are no active projects, or maybe I'm missing something.

At this moment, how could I fund a Drupal project?

What you're asking for is not an obvious task to get completed.

The most recent, fairly successful, funding campaign that I'm aware of is for upgrading the Rules module to D8, via #d8rules. For some pointers about it, start from the community promotion ad (disclosure: I posted it) which looks like so:

Depending on what the subject of your project is, maybe your project also fits the criteria for starting a similar ad ... free of charge (just a relevant image and URL will get you going)!