Drupal.behaviors function can't detect Views object when user is Anonymous Goals:
1. have a button in a View that refreshes that View via AJAX on click event.
2. Load refresh script only on pages that have View named "my_view".

I was able to achieve both of the following with the code shown below.

template.php

function mytheme_preprocess_views_view(&$variables) {
  $view = &$variables['view'];
  // Make sure it's the correct view
  if ($view->name == 'products_left_in_stock') {  //EDITED
    // add needed javascript
    drupal_add_js(drupal_get_path('theme', 'mytheme') . '/js/views-refresh.js');
  }
}

viewsrefresh.js

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

        var viewName = 'products_left_in_stock';

        // View is Ajax enabled,
        // and is available as a property of the Drupal object
        // like so...
        var instances = Drupal.views.instances;
        var targetedView;

        // iterate thru the various
        // views instances name to find your views
        $.each( instances , function getInstance( index, element){
                    if(element.settings.view_name == viewName ){
                            targetedView = '.view-dom-id-' + element.settings.view_dom_id;
                    }
        });

        // Define your button click here...
        $('.viewsrefreshbtn').click( function(){
                if(typeof targetedView !== 'undefined'){
                    $(targetedView).trigger('RefreshView');
                    console.log ('Clicked refresh btn on view. View Refreshed');
                }
                else {console.log ('Can\'t find viewName on this page');}
        });
    }
}
})(jQuery);

refresh button added to Views footer in Global Text

refresh

ISSUE IS: Refresh button works only for logged in users. When Anonymous user clicks Refresh button - following line from viewsrefresh.js executes

else {console.log ('Can\'t find viewName on this page');}

and nothing else happens.
Targeted View is present on a page and markup generated for that view is exactly the same as for logged in users. Seems like my function can not find the view when user is not logged in.

QUESTION: How can I make this function to detect targeted view when the user is not logged in? Am I missing something fundamental?

I understand this is a lengthy question. Greatly appreciate any insight on this if anybody has time to spare. thanks

I found that solution that works for me even under anonym.
Stars - changes

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

        **var viewName = 'ajax_test';**

        // View is Ajax enabled,
        // and is available as a property of the Drupal object
        // like so...
        **var instances = settings.views.ajaxViews;**
        var targetedView;

        // iterate thru the various
        // views instances name to find your views
        $.each( instances , function getInstance( index, element){
                    if(**element.view_name** == viewName ){
                            targetedView = '.view-dom-id-' + **element.view_dom_id**;
                    }
        });

        // Define your button click here...
        $('.viewsrefreshbtn').click( function(){
                if(typeof targetedView !== 'undefined'){
                    $(targetedView).trigger('RefreshView');
                    console.log ('Clicked refresh btn on view. View Refreshed');
                }
                else {console.log ('Can\'t find viewName on this page');}
        });
    }
}
})(jQuery);


How to add "load more" link to comments? I am trying to style my comments list to be similar to Facebook comments, so that user can load more comments by clicking on a link to load more. If there is a big number of comments then he should be able to load more and more comments.

Any suggestions how to start this?

Views Infinite Scroll and many similar modules allows you just that.

  Views Infinite Scroll provides a Pluggable pager that enables views infinite scrolling ( autopaging, depaging, endless pages ...you name it) by using jquery.autopager plugin. using this module with views page display will load another page whenever the user reaches bottom of the page.

Views Load More is other example.

  Yes, this is indeed, Yet another load more pager for views.

And you can show anything with Views. Comments too.


How to avoid CKeditor to change the HTML code? I want to add code like

 to make the whole block as a link, but after saving it getting changed to

. I am using CKeditor module, have done changes in config/text-format/filter HTML to disable the Limit allowed HTML tag. In short I want that editor do not do anything with HTML code.

I know that this is not the answer to your problem (which is annoying) but personally I would avoid putting a
 inside a  tag. It is normally not allowed to put a "block" type of tag inside an "inline" type of tag.

So you could do the following:

Your stuff

and then add a CSS rule:

a.block,
a.block > span {
  display: block;
}

This way you are HTML valid and CKEditor should not try to correct it.


Guzzle settings (base_url, user agent) I'm searching a way to configure Drupal's HTTP Client Guzzle. I.e. the base_url and user agent.

The Guzzle docs provide info here: http://docs.guzzlephp.org/en/latest/quickstart.html#creating-a-client

But nothing that works with the Drupal implementation.

I can see in core/lib/Drupal/Core/Http/ClientFactory.php that there is a default config with which the Guzzle Client constructor is fed.

//Line 46-65:

public function fromOptions(array $config = []) {
    $default_config = [
      // Security consideration: we must not use the certificate authority
      // file shipped with Guzzle because it can easily get outdated if a
      // certificate authority is hacked. Instead, we rely on the certificate
      // authority file provided by the operating system which is more likely
      // going to be updated in a timely fashion. This overrides the default
      // path to the pem file bundled with Guzzle.
      'verify' => TRUE,
      'timeout' => 30,
      'headers' => [
        'User-Agent' => 'Drupal/' . \Drupal::VERSION . ' (+https://www.drupal.org/) ' . \GuzzleHttp\default_user_agent(),
      ],
      'handler' => $this->stack,
    ];

    $config = NestedArray::mergeDeep($default_config, Settings::get('http_client_config', []), $config);

    return new Client($config);
  }

Any way to reconfigure this?

\Drupal::httpClient() does not provide any parameters for configuration.

There is no need to create your own Client or ClientFactory service.

Because ClientFactory::fromOptions() has

$config = NestedArray::mergeDeep($default_config, Settings::get('http_client_config', []), $config);

You can specify default options to Guzzle for all clients created by Drupal via your settings.php.  Core only provides an example of proxy settings, but you could alter the user agent via

$settings['http_client_config']['headers']['User-Agent'] = 'Foobar 1.0';

To create a single client with different options, (which will override settings from both ClientFactory::fromOptions() and settings.php), you can use the factory service directly:

\Drupal::service('http_client_factory')->fromOptions([
  'headers' => ['User-Agent' => 'Foobar 1.0'],
]);


How to implement one click upload? Drupal 8 supports multiple file upload, however the native interface requires three steps:

Select one or more files
Click Upload
Click Save

Ideally this could be simplified to a single step i.e. select one of more files, once done it uploads them. The user can delete a file later if they wish, but no point showing them the list of which they just select, just to make them change their mind.

How should one click upload for multiple files be implement in Drupal?

In pure PHP this can be done easily as follows (but Drupal 8 adds too many constraints for this to work):

<?php

$upload_dir = '/tmp/upload_test';
if ( ! is_dir( $upload_dir ) )
{
    mkdir( $upload_dir, 0777, true );
}

/** Rearrange the "parallel" _FILES array into consolidated file items. */
function rearrange( $arr )
{
    foreach( $arr as $key => $all )
    {
        foreach( $all as $i => $val )
        {
            $new[$i][$key] = $val;
        }
    }
    return $new;
}

if ( ! empty( $_FILES['data_fs_uploads'] ) )
{
    $files = rearrange( $_FILES['data_fs_uploads'] );
    print '
Copying uploaded files...
';
    foreach ( $files as &$file )
    {
        // File has 'name', mime 'type', 'tmp_name' path, 'error', and 'size'.
        $file['ext'] = pathinfo( $file['name'], PATHINFO_EXTENSION );
        $target_file = $upload_dir . '/' . $file['name'];
        if ( move_uploaded_file( $file["tmp_name"], $target_file ) )
        {
            print '
Copied ' . $file['name'] . '
';
        }
        else
        {
            print '
FAILED to copy ' . $file['name'] . '
';
        }
    }
}
?>

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input id="data_fs_uploads" type="file" name="data_fs_uploads[]" multiple="multiple" onchange="javascript:this.form.submit();" />
</form>

<?php
foreach ( glob("$upload_dir/*") as $file )
{
    print '
' . $file . '
';
}
?>

Here is how you would create an auto save after selecting an upload file(s) in D8.

upload_autosave.libraries.yml

auto:
  version: 1.0
  js:
    js/auto.js: {}
  dependencies:
      - core/jquery

upload_autosave.module

/**
 * Implements hook_form_alter().
 * Adds JS file to all forms
 */
function upload_autosave_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $form['#attached']['library'][] = 'upload_autosave/auto';
}

/js/auto.js

(function ($) {
  Drupal.behaviors.upload_autosave = {
    attach: function (context, settings) {
    if ($('.image-widget-data').length || $('.field--type-file').length){
      $('.js-hide.button.js-form-submit.form-submit').remove();
      $('form', context).on('change', 'input.form-file', function() {
        $('#edit-actions .button.js-form-submit.form-submit')[0].click();
        $(".details-wrapper").html("<img src='/modules/upload_autosave/images/loading.gif'>");
        $('#edit-actions').fadeOut(1000);
      });
     }
    }
  };
})(jQuery);


Is it possible to display a content type (availability calendars) inside a Forms API form? I read how FAPI is very flexible.  Well I started using it and after a few minor issues I have it working for a good deal of a multi-part form. (Using #state and fieldset)  Now I want to embed an Availability Calendar in the form and I can not figure out if it is possible.  The newest Availability Calendar is based on entities and fields.  My FAPI/module form is just that, a straight forward form.  To expose an Availability Calendar I have to create a content type.  So I am stuck with a content type instance and my own form module, trying to figure out if I can merge the 2.

I'd really like to keep the calendar inside the form in its own collapsible section (via fieldsets), only exposed in the UI when the user has selected other info. This means I either embed Calendar inside a form, or possibly a form inside the Content Type.

Any pointers ?  Am I missing something to glue these parts together? I considered EntityForms but it doesn't seem flexible enough to make nicer forms. (radios?)  My only solution may mean splitting Avail Calendar off on its own page and make it part of a series in a multi-part form.

I don't mind writing php, I am likely going to modify Availability Calendar booking formlet.

To add a form inside already existing form you can try out the following:

$form['another_form'] = array(
'#markup' => drupal_get_form($form_id);
);


What is the correct way to rename an uploaded file using tokens? I am building a webform. I have a Name field that uses first and last name.
I have an image upload field where I want to rename the image to lastname-firstname.jpg.
In the properties for the file upload, I selected Rename files for the pattern [webform:element:name:last__title]-[webform:element:name:first__title].
When I test this using John Smith, the file is getting renamed, but it is being renamed to last-name-first-name.png instead of smith-john.jpg.
I'm guessing I'm doing something wrong with the pattern, but I don't know what.
This is the field definition.
name:
  '#type': name
  '#title': Name
  '#title__access': false
  '#first__title': 'First Name'
  '#middle__access': false
  '#last__title': 'Last Name'
  '#suffix__access': false
  '#degree__access': false

I had the same issue. The answer was buried way down in Browse available tokens.
I wanted to rename an uploaded file based on the responses to the last_name and first_name fields. The pattern that worked was [webform_submission:values:last_name]_[webform_submission:values:first_name].


Optional configuration and order of enable modules on profile I have a bug or a misconfiguration I don't understand. I'm creating a profile to create new web sites with an advance configuration quickly. But I meet a bug during installation with dependencies of with some configurations.

On image style, I add a manual `crop type than I add on the majority image style. For example, my file for image style large is:

langcode: fr
status: true
dependencies:
  config:
    - crop.type.crop_1x1
  module:
    - crop
name: large
label: 'Large (480×480)'
effects:
  ddd73aa7-4bd6-4c85-b600-bdf2b1628d1d:
    uuid: ddd73aa7-4bd6-4c85-b600-bdf2b1628d1d
    id: image_scale
    weight: -9
    data:
      width: 480
      height: 480
      upscale: false
  7cd03233-541d-472e-851c-de8945ee6709:
    uuid: 7cd03233-541d-472e-851c-de8945ee6709
    id: crop_crop
    weight: -10
    data:
      crop_type: crop_1x1

I put all images style configuration file in the directory optional in config directory. My configuration files for crop and the crop type are in the install directory. Despite this, when I test my installation, I have always the error message :

  Drupal\Core\Config\UnmetDependenciesException: Configuration objects provided by image have unmet dependencies: image.style.large (crop.type.crop_1x1, crop) in Drupal\Core\Config\UnmetDependenciesException::create() (line 98 of /var/www/html/core/lib/Drupal/Core/Config/UnmetDependenciesException.php).

I have no configuration which are dependent of image module in install directory. Image module is always enable before Crop module instead of to respect dependencies. I tried to put my configuration files for crop in optional but it doesn't fix the problem, I don't know if change the order of modules in dependencies of my profile have an influence. I try without success.

I don't see where is the error in my installation.

Update: This problem happens only with default configuration of image module, that is image.style.large, image.style.medium and image.style.thumbnail which are the native configuration. I have other styles which are import later, after crop module is enable and configure as expected. I don't know if it's a bug of the configuration manager which try to import necessary default configuration files even if they are in optional.

My problem is a bug of the configuration system. An issue exists for this exact problem: https://www.drupal.org/project/drupal/issues/2922417


Bootstrap theme doesn't work on mobile device (but work on computer, even when resize browser to min width) While on mobile device:

Main Menu (the default one): On top I see the site name with beside the "toggle navigation" button (which don't respond) and above a vertical list of
menu items. And the menu has no more border, background-color, etc...
Views carousel: I see a vertical list of images id ("1.", "2.", "3.", etc...) and above a vertical list of my images.

I tried from another mobile (mine is nexus 4) and the problem doesn't appear.

Finally, I installed the module bootstrap_library and the problem disappeared.


Programmatically Update Geofield Data My setup is:

Addressfield on nodes to collect address data
Geofield using "Geocode from another field" choosing the addressfield and the Google Geocoder

When I edit/save a node in the UI, the data is geocoded.  However, I have thousands of nodes and am trying to write a script to update the geocode info on each node.

I tried loading all the nodes and doing a node_save() but the geocode hooks didn't fire.

How can I programmatically update the geofield information?  Is there a hook I can use?

According to README.TXT:

  API NOTES

  Geofield fields contain nine columns of information about the geographic > data that is stores. At its heart is the 'wkt' column
  where it stores the full geometry in the 'Well Known Text' (WKT)
  format. All other columns are metadata derived from the WKT column.
  Columns are as follows:

  'geom'         Raw value. By default, stored as WKB, loaded as WKT
  'geo_type'     Type of geometry (point, linestring, polygon etc.)
  'lat'          Centroid (Latitude or Y)
  'lon'          Centroid (Longitude or X)
  'top'          Bounding Box Top (Latitude or Max Y)
  'bottom'       Bounding Box Bottom (Latitude or Min Y)
  'left'         Bounding Box Left (Longitude or Min X)
  'right'        Bounding Box Right (Longitude or Max X)
  'geohash'      Geohash equivalent of geom column value

  When a geofield is saved using the provided widgets, these values are
  passed through the geofield_compute_values function in order to
  compute dependent values. By default dependent values are computed
  based on WKT, but this may be overriden to compute values based on
  other columns. For example, geofield_compute_values may be called like
  so:

  geofield_compute_values($values, 'latlon');

  This will compute the wkt field (and all other fields) based on the
  lat/lon columns, resulting in a point. As a developer this is
  important to remember if you modify geofield information using
  node_load and node_save. Make sure to run any modified geofield
  instances through geofield_compute_values in order to make all columns
  consistent.

This translates to:

      $spot->field_coordinates[LANGUAGE_NONE][0] = geofield_compute_values(
          array(
              'lat' => $venue->location->lat,
              'lon' => $venue->location->lng,
      ), GEOFIELD_INPUT_LAT_LON);


Inserting additional AJAX using hook_flag I'm trying to insert additional AJAX commands when a Flag link is toggled.  The flags link type is 'JavaScript toggle'.

Hooking into the Flag callback seems simple enough using hook_flag.

function hook_flag($op, $flag, $content_id, $account, $fcid) {

    if ($flag->name == 'flag_name') {
        // Additional Ajax Commands
    }

}

The AJAX command I'm looking to include is:

ajax_command_replace("#div_id_to_replace", 'New content');

Is it possible to insert AJAX using hook_flag?  If not, what would be the most appropriate way to swap out div content (in addition to the actual Flag AJAX) without a page reload when a Flag link is toggled?

Update: Found the Flag API (JavaScript) page while crawling through the docs. Hopefully will have an answer to add shortly.

I'm certain there is a better way to do this, but rather than using hook_flag use JavaScript.

The trick seems to be to use bind('flagGlobalAfterLinkUpdate', function(event, data)

And then catch the specific flag you're using with data.contentId;

(function ($) {
    $(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
        var fsrnid=data.contentId;
        var fsrpostcard = $(".postcard-" + fsrnid).text();
        var fsrpostcardset = fsrpostcard.indexOf('Yes') >= 0;
        var fsrcalled = $(".flag-customer-called-" + fsrnid).text();
        var fsrcalledset = fsrcalled.indexOf('Yes') >= 0;
        var fsremail = $(".flag-email-sent-" + fsrnid).text();
        var fsremailset = fsremail.indexOf('Yes') >= 0;

        if (fsrpostcardset || fsrcalledset || fsremailset) {
            $(".completed-" + fsrnid).text('Yes');
        } else {
            $(".completed-" + fsrnid).text('No');
        }

    });
}(jQuery));

The Flag API (JavaScript) documentation is a bit dated and doesn't necessarily apply directly to Drupal 7.  It is still very useful in figuring out how the Flag module uses JavaScript though.


Can anyone help me translate this Javascript code line the Drupal Way? I need to convert this code line (it focuses the cursor to the first input of a form) to Drupal behaviourism. Can anyone help me put it the Drupal bushido way?

jQuery("input:text:visible:first").focus();

jQuery("input:text:visible:first").focus();

Becomes

Drupal.behaviors.focustextfield = function(context) {
  $("input:text:visible:first:not(.focustextfield-procd)", context).addClass("focustextfield-procd").focus();
}


Trimmed body field only show first paragraph (update: it not a problem relate to uppercases)
I think I found a bug but not sure which module is causing it. Maybe CCK...

I have a content type with the body field set (through manage display) to be shown as Trimmed to lenght: 400

Then I created a node with 2 paragraphs of text in the body . When I load the full view of the node the trimming only shows the first paragraph

the trimming works fine if I enter this text in the body:

some text, some text, some text, some text, some text, some text, some text, some text

the trimming also works fine if I enter this text in the body (notide that the second paragraph is a short paragraph)

both paragraph are shown
some text, some text, some text, some text, some text, some text, some text, some text

but only the first paragraph is shown if I enter this text in the body (notice that the second paragraph is longer)

only this paragraph is shown
some text, some text, some text, some text, some text, some text, some text, some textsome text, some text, some text, some text, some text, some text, some text, some textsome text, some text, some text, some text, some text, some text, some text, some textsome text, some text, some text, some text, some text, some text, some text, some textsome text, some text, some text, some text, some text, some text, some text, some text

How can I solve this?

Your best bet is a custom formatter. Create a custom formatter with the custom formatters module:

  The Custom Formatters module allows users to easily create custom
  CCK/Field Formatters without the need to write a custom module. Custom
  Formatters can then be exported as CTools Exportables/Features or
  Drupal API Formatters.

Once installed just write some php code and format and insert the particular text that you're looking for.


Drupal post to facebook Is there a way to make Drupal post to facebook?

I want the user to be able to create an article, and when user does that, it automatically posts information of the new article to a Facebook account. Is this possible?

You should check out Facebook Autopost. There is a video tutorial on how to set up everything to do it easily.

With this module you will be able to post Links, Posts, Events, Questions, … linked to Drupal events.


Webforms: Is it possible to set a delete field button? As far as I understand there is not possible do delete the field value of file upload fields but rather replacing the field with an empty one.

Is it possible to add this button using JS and thus delete the text path inside the field without refreshing the page (PLAIN SIMPLE)? Otherwise I am afraid i need to use a php solution with page refresh.
If not is it possible for 'Delete' to emulate the 'Browse' button? I mean when hitting 'Delete' to actually browse for another file?

ps. I know webforms are using their own implementation but I am force to find another solution

This link seems to have some solution. Clear upload file input field with jQuery

The relevant js is given below.

  The HTML of any element can be reset with jQuery using the following
  function and passing in the id of the element's parent. This will
  reset the HTML within the parent to its original state; it will lose
  any binding you'd added after the DOM was loaded (such as adding an
  event handler in $(document).ready). Here's the Javascript for doing
  this:

function reset_html(id) {
    $('#'+id).html($('#'+id).html());
}

  In $(document).ready we can now add a div around every  element with a clear button, binding a function to it
  which will reset the HTML of the div like so:

$(document).ready(function() {

    var file_input_index = 0;
    $('input[type=file]').each(function() {
        file_input_index++;
        $(this).wrap('

');
        $(this).after('<input type="button" value="Clear" onclick="reset_html(\'file_input_container_'+file_input_index+'\')" />');
    });

});

Note : I have not tested this out myself.


How do I show a link to the user registration page only to anonymous users? I want to show anonymous users a "Register" link.

So, in mymodule.menu.yml:

mymodule.userregister:
  title: 'Register an Account'
  url: 'internal:/user/register'
  weight: 10
  menu_name: account

This adds a register link to the account menu next to the login/logout link-- great!  Except it also shows up for authenticated users, who get an "access denied" error if they click it.

I looked in user.links.menu.yml in code/modules/user to try to find something I could use:

user.page:
  title: 'My account'
  weight: -10
  route_name: user.page
  menu_name: account
user.logout:
  weight: 10
  menu_name: account
  class: Drupal\user\Plugin\Menu\LoginLogoutMenuLink

I also checked user.routing.yml:

user.register:
  path: '/user/register'
  defaults:
    _entity_form: 'user.register'
    _title: 'Create new account'
  requirements:
    _access_user_register: 'TRUE'

user.logout:
  path: '/user/logout'
  defaults:
    _controller: '\Drupal\user\Controller\UserController::logout'
  requirements:
    _user_is_logged_in: 'TRUE'

I'm stumped.  How can I make my menu link only show up for anonymous users?

According to Structure of routes

  _role: A specific Drupal role, eg. 'administrator'. You can specify multiple ones via "," for AND and "+" for OR logic. Note that, since
  the roles available may differ between sites, it's recommended to use
  permission based access restriction when possible.

so try

requirements:
  _role: anonymous


What's the difference between creating a 'Content' or a new 'Pages>>Add Custom Page'? I'm working on a pre-established site. I've noticed that I can add new 'Content' (Content>>Add Content) or I can add a new Page (Structure>>Pages>>Add custom page).

The site seems to use an indiscriminate amount of both, though Content seems to be used more with templates for blog and product pages.

What are the differences between the two and in what scenarios should I use them?

Structure -> Pages menu link comes from ctools and it allows you to create more complex pages than your basic drupal core ones (Content -> Add Content link). This may include components comming from other modules (Panels, Fieldable Panel Panes, Views Content Panes and many other that intergrate with Ctools).

With Page Manager (and panels in general) you can create more complex versions of a page (or more, if you use the right contexts).


How does Feed import get a list of the CSV fields to map to content type fields? I am using Feed import to load a CSV file exported from an SQL database into Drupal and I am stuck at the stage where  I need to map the CSV field names to the Drupal content type field names.

I think there as to be some stage in the process where in some form or dialog I can input a list of the CSV field headers and proceed to a form which enables me to match the CSV headers to the field names of the content type, but I can't find such a page in the list of pages I have to follow.

I am sure I have followed the Feed Importer creation process properly. Am I missing something, or this capability not included in the Feeds CSV importing system??

https://www.isovera.com/blog/using-feeds-module-bulk-import-drupal-7

This is what I used...worked like a charm...you simply need to map field names from CSV file to node fields...

Alex


stream wrapper public /private not found Error Configuration : WAMP on windows drupal 7

I have tried using

$image = file_get_contents('E:\Team_Install\wamp\www\rootfolder\sites\all\modules\my_module\errorwinmobilesdk.jpg');
$file = file_save_data($image, 'public://',FILE_EXISTS_REPLACE);

I can see the result after first line file_get_contents but on file_save_data I get that destination folder invalid error

Another method I had tried was  $file = file_copy($source, $dest);

here also it says $dest does not exists
Wrapper folder permission and path are check thorughly they are working when I add an image using media_gallery module as it saves to public gallery or creates a new article with image, when I try to add from code it breaks and start showing message

  The data could not be saved because the destination public is
  invalid. This may be caused by improper use of file_save_data() or a
  missing stream wrapper.

Please help I am new to drupal and stuck at this.

Thanks in advance

I had this problem too after some coding with file_save_data. And i solve it after clearing the cache and resaving the path in the file system configuration at admin/config/media/file-system.

My problem comes from an add field of file type, programmatically in an update.


Views Rss - How to set pager options / items to display via URL argument I have a RSS feed being built by the Views RSS module. I can configure the pager to display a certain number of items; however, some consumers of my feed only want a few of my latest items from my feed. So I need to pass a limit in the URL to the number of items in my feed.
something like this:

www.mywebsite.com/rsslatestnews/50 - For 50 items.
or
www.mywebsite.com/rsslatestnews/2 - For 2 Items.

I've tried implementing the hooks:

hook_views_pre_build
hook_views_post_build
hook_views_pre_execute
hook_views_post_execute
hook_views_pre_render
hook_views_post_render

To no avail, I think the RSS Views module is in some way skipping
the typical order views hooks are triggered.

My question is this:

Which hook can I use to set the limit of items displayed by my RSS view?

/**
 * Implements hook_views_query_alter.
 *
 * If we have an rss feed view we need to set pager settings from url.
 * If no pager number specified in the url do nothing and use view pager   settings.
 * Otherwise get the items_per_page options from the first argument in the url.
 */

function rss_feed_length_views_query_alter(&$view, &$query) {

  $rss_views = array(
    'rss',
  );

  if (in_array($view->name, $rss_views)) {
    $limit = arg(1);
    if ($limit !== NULL) {
      $view->set_items_per_page($limit);
    }
  }
}

SUGGESTED IMPROVEMENT:

  "i'd have used GET parameters rather than path elements - since it's not a different resource, rather it's an option"

I'll accept as an answer anything that implements the suggested improvement.  :)


I cannot translate the action label I'm using Umami profile and choose Spanish is default language. Almost of the interface has been translated into Spanish. But some places did not translate like user page.

I'm going to admin/config/regional/translate to check. But This text already translated, but UI still show English text.

I try debug to find the reason. I was break point at line 340 of line drupal/core/modules/views/src/Plugin/views/field/BulkForm.php and found that $action->label() return English string.

Because at line 116 $this->actionStorage->loadMultiple() return all actions. In this some actions return English string, some actions return Spanish string (example install module pathauto, this action return Spanish). All actions when install profile will using English text and module install after will be translate.

I don't know why. And How to can translate label of actions?

To translate action labels install the core module Actions and go to /admin/config/regional/config-translation/action.

Actions are config entities, which you can translate in an exported config as well, if you don't want to install the UI option.


Drupal messages won't disappear I don't understand why, but my Drupal messages won't disappear, they just get "added" to each other. Someone has posted a similar problem on drupal.org: "warning/error messages won't disappear", but no solution has been posted yet. There's another one which is almost the same: Drupal messages won't go away.

Here's an example of the problem:

I do have the Administration menu installed, but the problem didn't occur earlier, so I don't think this is the source of the problem.
I've already cleared cache, ran update.php, ran cron, so I'm out of ideas.

I recently installed Ubercart module, but I don't know if it has anything to do with my problem.
But there's another one which I also don't understand: if I try to open a page which doesn't exist, I don't just get a "Page not found" error, but many MySQL errors too, which looks like this: (1) (2). It's really unhealthy too... Maybe there's a connection between these problems.

Any ideas?

Thanks!

Messages are kept in the user's session, which by default is stored in a database table called 'sessions'. If your database server dies partway through the page request, the messages may not get cleared from the session.

You can see the MySQL server failing when updating the sessions table in this image due to a max_allowed_packet error.

1M is a very small max_allowed_packet for a Drupal installation. You may need to ask your host to increase this limit. Alternatively, you could turn off dblog and use syslog instead, which sends your Drupal logs to a system daemon - but this may require your host to set up a syslog location for you.

There may be a module that implements hook_watchdog() that can save logs to a standard file. I can't find one, but if one exists, that could be a good option in your situation too.


Related content in a view using entity reference I've browsed through (and tested) every solution I could find here to this seemingly simple challenge.

I've got multiple content types (fx. News, Releases, Events, Videos etc.) that are referencing the content type "Artists" using an entity reference-field.

I want to have related content-blocks that shows the related news, releases etc. for the artists references in the node.

I've done this in D7 but it seems the approach have changed a bit since then (?).

What I thought I should do (with content type 'release' as example:

Create a related release-block in views
The a relationship 'Content using field_artist', require this relationship
Add contextual filter, select relationship, select 'content id from URL' as default value

But no results appear when doing this. If I remove the relationship I get 1 result, the node I'm already on...

What am I doing wrong?

As mentioned in the comments you don't need any Relationships to filter out the related content. Simply add the Contextual filter for your Entity Reference field, and configure it with a Default value to pick up Content ID from URL, and validation criteria to the Artist content.

You can use the Relationship if you need information other than the Artist node ID in your Views, for example, if you have an independent Views Page showing all Releases, and you want your Contextual filter to be in your URL showing the Artist name and not the ID number:

/releases/Beatles

for all Releases nodes referencing the Artist Beatles.

And it's still working the same as it did in Drupal 7, apart from the different wording in the names, you just added the wrong Relationship.

It should not be the 'Content using field_artist', but Content referenced from field_artist.

'Content using' that field are the nodes with the ER (News, Releases, etc.) so you're just pointing back to what you already have in your Views. This is a "backwards" Relationship.

The 'Content referenced from field_artist' Relationship is pointing towards the Artist nodes, and through adding that Relationship you'll have the Artist data available in your (Releases) Views. This is the Relationship you want to you in this case.


How can I disable the cache for a specific page or have the cache ignore query params? I need to disable the cache for a specific page, or get the cache to ignore query params. I have tried this, but it does not disable the cache for me https://www.drupal.org/project/page_cache_query_ignore
After trying multiple ways to disable the cache for a specific page or even the whole site I have nothing that works.
I have tried all of these in settings.php
$settings['cache']['default'] = 'cache.backend.null';
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';
$settings['cache']['bins']['page'] = 'cache.backend.null';
$settings['cache']['bins']['entity'] = 'cache.backend.null';

There is also talk of using \Drupal::service('page_cache_kill_switch')->trigger(); but I am unsure where to place this to disable the cache for a regular page.
This is for the search page, that uses query params for the search query. Drupal 8 is caching the page so each visit to the search after the first search always shows the results for the first search.
The header for Drupal dynamic cache is always a HIT
X-Drupal-Dynamic-Cache:    HIT

After a lot of trying and retrying I settled on the following solution
function mythemename_preprocess_page(&$variables)
{
  if(isset($_SERVER['QUERY_STRING'])) {
    $params = \GuzzleHttp\Psr7\parse_query($_SERVER['QUERY_STRING']);
    if(isset($params['keys']) && strlen($params['keys']) > 0 && preg_match('#^/search#', $_SERVER['REQUEST_URI'])) {
      \Drupal::service('page_cache_kill_switch')->trigger();
    }
  }
}

As far as I can tell, this stops the cache from working if the request is on the search page and there is a query parameter present named keys


Rule to deselect checkbox item? I have a mailchimp subscription content type that add a user to the email list in mailchimp. It works great and adds them to the list.

However, I want deselect that checkbox when they fill out a second content type with a rule.

So, on creation of content type unsubscribe, check mailchimp list and remove email from list.

I have been search for ideas everywhere and cannot find anything in a tutorial or in Drupal Stack Exchange. Looking for ideas to try and hopefully figure out. Thanks!

if you wont find any other solution without coding to deselect that checkbox you can try to do it via your custom module (if you don't have any you will have to make one - that's different story).

function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id){
  $form['field_order_details']['und']['0']['value']['#resizable'] = FALSE;
}

Something similar should work for your checkbox.

See hook_form_alter().


How to prevent recursion when setting a data value for a user in rules? I have a rule that is triggered on the event After updating an existing user account.  The rule performs an action, Set a data value, that changes one of the values of the user account fields.

However, doing this causes the user account to be saved again, which triggers After updating an existing user account a second time.  This causes some of my other rules that are triggered after updating a user account (such as those for sending notification e-mails) to be triggered twice.

I know this Set a data value rule is the issue because when I disable it, the account is only sent once, and the other rules that send notifications only send a single notification.

Is there a way to avoid this (single) recursion when setting a data value with a rule?

Your question seems like a variation of the question 'Why is my rule that reacts on event "After updating an existing user account" firing twice?'. The accepted answer in that question might help to understand your issue (what's causing it) also, ie:

  some other module code is calling a user_save on hook_user_update triggering the rules event a second time.

That question also has another answer with a very interesting workaround, with an image which looks like so (a picture is worth more then 1000 words):


How to make custom Drush commands to work on remote instance I have developed custom Drush commands that includes some shell commands all which work locally. I would like them to work also on the remote instance with aliases that have the remote settings. Here is how the shell commands are currently executed:
//executes command

function execute_command($command)
{
    drush_log(dt('COMMAND: @command', array('@command' => $command)), 'notice');
    //any shell command fore example 'cp some/source dest/dir','tar xvf some.tgz',etc
    drush_shell_exec($command);
    drush_log(drush_shell_exec_output(), 'debug');
}

So, I would like to wrap this into some Drush API so they also execute on remote instance. Is it possible? How should I make the shell commands part of my custom Drush commands to run on the remote instance when user does something like:

drush @remote-alias custom-command

Thank You

I believe the remote site also has to have the commands as well in order to execute successfully.


Features menu import/export I am having an issue with exporting my main menu with the features module. I go to features > module_name > recreate > menu_links and then check all the links that I want.
Once I import the feature on a fresh instance, not all of the menu links show up. If I go to features > module_name > overridden > menu_links all of the links show up there but when I click revert changes, nothing happens

This is a couple months late, but I encountered the same issue and wanted to answer this in case someone runs into the same problem.

Basically, Features will not show menu links unless the link path is identical.  So, the paths on the site you're importing to have to be identical to the ones from you're exporting from.  If they are different, nothing shows.

If you open up the links.inc file you'll see:

 $menu_links['menu-primary:node/1'] = array(
   'menu_name' => 'menu-primary',
   'link_path' => 'node/1',

You can manually modify the link path to make things show up, but obviously this isn't ideal.  Hopefully this gets addressed down the road...really a killer in my opinion.


How do I get the correct URL of an image field? I'm trying to print out the URL of an image field using the following code.

<img src="<?php echo $field_company_logo['und'][0]['uri']; ?>" alt="<?php echo $company[0]['#markup']; ?>" />

The code gives me a URI like public://company-logos/image.png when I would need sites/default/files/company-logos/image.png.

What code should I use to print the image path (i.e. sites/default/files/company-logos/image.png)?

You want to use the drupal_realpath() function to convert the URI into the actual filesystem path.

echo drupal_realpath($field_company_logo['und'][0]['uri']);

You could also use file_create_url() to get the actual URL to the image, as opposed to a local filepath.

And the correct way to render an image is to run it through theme_image():

echo theme('image', array(
  'path' => file_create_url($field_company_logo['und'][0]['uri']),
  'alt' => check_plain($company[0]['#markup']),
));

Also, accessing field data the way you're doing it isn't the preferred method. Have a look at field_get_items() and the detailed example in the Rendering Drupal Fields (the right way) blog entry.


What is the command that replaces 'drush variable-set'? In Drupal 8 the Drush command drush variable-set no longer works.

From reading (here) it appears that Drupal 8 has a new "configuration" system that replaces the old (Drupal <=7) "variables". But what is the new Drush command to achieve the same ends?

Specifically I want to convert the commands:

drush variable-set site_mail someone@email.com
drush variable-set update_notify_emails someone@email.com

to the new Drupal8/Drush8 equivalent...

Following some more research it seems the new command is:

drush config-set <config-name> <key> (where the old format was drush variable-set <name> <value>). Alias: cset.

So I'm not totally sure that I have this right (so comment and/or another answer from someone who does would be great...), but it seems that the config that includes emails are: contact.form.feedback recipients, update.settings notification.emails and system.site mail.

This update is the result for some good discussion (below).
Note that some settings are arrays (rather than strings):

www/drupal8# drush config-get update.settings notification
'update.settings:notification':
  emails:
    - admin@example.com
  threshold: all

to update this you need to run:

drush -y config-set update.settings notification.emails.0 admin2@example.com

Source: Leverage Drush 7 for Drupal 8.

Note: Drush 7 no longer supports Drupal 8, but this still applies.


How to use cookies in Drupal? I am writing a module that allows users to put comment on each paragraph.
So in my module I have added a new field to comment table called "paragraph_id" and I have also added a new field to comment form that say:

 Which paragraph do you want to put comment on?

After each paragraph I have added a link saying:

  Put comment on paragraph 1 (2,3, ...., the number changed based on the number of the paragraph.

in order to this, I have written the following in node.tpl.php:

        for ($i=1;$i<$number;$i++) {

        print render($paragraphs[$i]);
       ?>

      Put comment for Paragraph <?php echo $i?>

    <?php

I want to do one the following options:

1) Eliminate the new field which asks for the number of the paragraph from comment form, and do something that when a user for example clicks on a link like:

   Put comment on paragraph 1

, the number "1" automatically got save in comment table in "paragraph_id" field.

2) Or  keep the field that asks for paragraph number in comment form and when user clicks on a link like

 Put Comment on Paragraph 1

while he is getting directed to the comment form, the value of that field (paragraph_number in comment form) sets to 1.

How can I do it?

Drupal automatically ensures that a user has a session, so your script can simply read and write to the $_SESSION superglobal array.


URL aliases problem when assigning aliases for custom pages I have created some content type page around 10 pages after that I started creating custom page like page-node-11.tpl.php. I want to assign node number 11 to my newly created page but when a assign node/11 it will give me error msg

The path node/11 is either invalid or you do not have access to it

How to overcome this error ?

You are doing it in reverse order. This order is generally followed.
Create a page.
Note down the node number (ex : 7)
Then create a file corresponding to that like page-node-7.tpl.php
You should not assign node/11 as alias as these are considered as internal paths.
You can give anyother name which mostly suits the page contents.


When can uid 1 get an access denied page? I am having a very strange problem that I can't track down.

We have been working on a custom site for a client now for several months.  Theme is a Zen subtheme.

I can't remember the last time I tried to access it, but I am getting an "access denied" when I try to view /admin/build/themes/settings/mysubtheme, even as uid 1.  It is getting logged this way, too, so I think it really is an access denied.  I can access this page for Zen, Rootcandy, and other enabled themes.

I have done all of the usual tricks for attempting to fix this (run cron, clear cache, rebuild node perms, assign all perms to my superuser role, etc) without luck.

A theme-settings.php exists for the theme and all of the hooks are named properly for the theme.

How is this possible since user_access returns TRUE when uid==1?

Thanks.

After trying to fix this for an hour, I tumbled on the solution right after I posted this.  Apparently, it is possible to set a theme as "default" but not have it "enabled", and have a site function normally.  Enabling the theme fixes the problem.


How can I use postsave method extending WebformHandlerBase for submitting to account fields I created a webform handler class extending from WebFormHandlerBase: The method, postsave has the following code:

public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
    $account = \Drupal::currentUser();
    $user = \Drupal\user\Entity\User::load($account->id());
    $user->addRole('example');
    $user->save();
  }

A boolean and photo value are submitted by the webform submission.  I need to submit the boolean and photo to account fields.  How do I do it?

$account = \Drupal::currentUser();
    $user = \Drupal\user\Entity\User::load($account->id());
    $data = $webform_submission->getData();
    $photo = $data['picture'];
    $user->set('field_photo', $photo);
    $user->save();
  }
The above code, for example, will take a webform element, key is 'picture' and set it to an account field, 'field_photo'.


Webform email twig template questions What is the correct syntax to test if a file has been uploaded in a webform in a twig email template?

For a text area, {% if webform_token('[webform_submission:values:question_text_area:value]', webform_submission) %} works fine but to test if a file has been uploaded, {% if webform_token('[webform_submission:values:join_a_file:value]', webform_submission) %} does not work.

Also, when there's a file uploaded, I want to display in the email only the title of the file ... {{ webform_token('[webform_submission:values:join_a_file:delta:format:value]', webform_submission) }} works but it outputs a link to that file. Is it possible to just have the text of the file name?

Thanks!

That is a great question.

Getting just the filename is not currently supported but you can pull the file's URL using [webform_submission:values:join_a_file:delta:format:url]

The current list of supported formats for uploaded files is here. I created a ticket to
add machine name to element submission display formats so that this information is exposed to site builder.

If you need just the file name, please create a new ticket in the Webform module's issue queue.


How do I define a custom html.html.twig file? I need to define custom html.html.twig file for particular url. What I did is given below:

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return array(
    'html__ajax' => array(
      'render element' => 'elements',
    ),
  );
}
/**
 * Implements hook_theme_suggestions_HOOK().
 */
function mymodule_theme_suggestions_html(array $variables) {
  $template_suggestions = array();
  // This is used to display only ajax $content.
  if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
    $template_suggestions[] = 'html__ajax';
  }
  return $template_suggestions;
}

I have copy pasted html.html.twig file from my theme and put it inside my module's template folder and renamed it as html--ajax.html.twig. Changes are reflecting fine but not all default variables are not available in my custom html.html.twig file.

When I open the page I can see the content till Skip to main content link. Please help me what I am missing while declaring custom template file.

If you want to return 'render element' this would be 'html':

'render element' => 'html',

But you probably don't need this, better return the base hook so that drupal fetches the variables from the hook html:

function mymodule_theme() {
  return array(
    'html__ajax' => array(
      'base hook' => 'html',
    ),
  );
}


Store custom checkout pane data to order I've created a custom checkout pane according to documentation. When I submit my Order and go to admin page, where all my orders are listed, I can't see this custom pane field there. I've already tried to add $this->order->save(); at the end of submitPaneForm function but that seems to make no difference. I've already created field with machine name "field_test_me" in my Order type and also have added this field to enabled fields on "Manage display" tab, but the field seems to be empty.
Is there anything I'm missing to get my custom pane fields to be displayed on the "Order detail" page, please?
This is how my buildPaneForm function looks like:
public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form)
{
$pane_form['billing_info'] = [
  '#type' => 'fieldset',
  '#title' => $this->t('@title', ['@title' => $this->configuration['title']]),
];

$pane_form['billing_info']['field_test_me'] = [
  '#type' => 'textfield',
  '#title' => 'Test me',
  '#wrapper_attributes' => [
    'class' => ['col-md-6']
  ],
  '#default_value' => 'MY CUSTOM STRING'
];
return $pane_form;

}
And this is how my submitPaneForm function looks like:
public function submitPaneForm(array &$pane_form, FormStateInterface $form_state, array &$complete_form)
{
    $values = $form_state->getValue($pane_form['#parents']);
    $this->order->setData('field_test_me', $values['billing_info']['field_test_me']);
}

I'm using other functions for displaying value on "Review" page, but those are not part of my issue.

I found a solution. With my custom field called "Test me" and machine name "field_test_me" created in my Order Type entity I could save the data from Custom Checkout Pane with $this->order->set() function instead of $this->order->setData(). Of course I needed to change $this->order->getData() to $this->order->get() everywhere where used.
I don't understand what's the difference between set() and setData(), but it seems to store my Custom Checkout Pane values to my custom fields created in my Order type entity.


remove email field from registration form From core\modules\user\src\AccountForm.php, user module developer added following comment to Email fields.

 // **The mail field is NOT required if account originally had no mail set**
    // and the user performing the edit has 'administer users' permission.
    // This allows users without email address to be edited and deleted.
    // Also see \Drupal\user\Plugin\Validation\Constraint\UserMailRequired.

    $form['account']['mail'] = array(
      '#type' => 'email',
      '#title' => $this->t('Email address'),
      '#description' => $this->t('A valid email address. All emails from the system will be sent to this address. The email address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by email.'),
      '#required' => !(!$account->getEmail() && $user->hasPermission('administer users')),
      '#default_value' => (!$register ? $account->getEmail() : ''),
    );

I do not understand what is "originally had no mail set" mean.
it looks like , there is a config option which can turn off Email requirement, but I am unable to find the config option.

Mean that you can set an account without e-mail, as admin or someone that have rights, in url '/admin/people/create'. But when a visitor goes to 'user/register', he must specify a e-mail, because someday an e-mail will only be used if you wish to receive a new password, as description says.

There are two types of accounts, one with e-mail (like a visitor that created a new account), and another without e-mail (admin created a new user). This is why AccountForm check if user have an e-mail and check if user is admin or have 'users' permission, to set e-mail field required or not.

There is no reason to a visitor create a account without an e-mail, there is no other way to admin/system contact him for any kind of situation. In other hand if an admin create a new user, somehow he will able to contact the new user.


Webform, creating customized directories for uploaded files Newbie and my first question on here. I'm still learning Drupal. So apologies if I missed anything

Here is my issue
I am using Webform to create an upload page. The user enters an ID(text field) and uploads the file. The file gets uploaded to a private section on the server. Now I am trying to make sure that the file gets uploaded into this separate folder(named after the ID)( say all/private/ID/). Can I do that using a Webform ? For now, all I can use are basic tokens,not values I can grab from other fields(ex: %username) to create these directories.

If webforms are not the answer, what else would be a good method to go about it ?

Greetings welcome to the land of Drupal stuff :)

In general here are some tips:

creating a folder off of a textfield ID is going to be cumbersome. How will you know subsequent users aren't putting in the same ID and or overwriting eachothers files?
Webform has an API of available hooks. For instance look at webform_submission_presave() which allows you to change/capture a users submitted answer and alter it; you could likely alter the destination of the file to be saved, and assure the destination directory exists with a Drupal API function file_prepare_directory.

If you're looking for an all-in-one no code solution. Look at this issue queue PATCH for webform that looks like it supports custom tokens for upload files.


How to use articles attached images as background of a div I'm doing my first site on Drupal 8 and I have a problem. I would like you to help me.

In fact I'm trying to get the articles attached images as a background for a div created in the page templates.

I wrote this code in my theme.file

function THEME_preprocess_page(&$variables, $hook) {

// Set articles attached img like background
$node = Drupal::request()->attributes->get('node');
if($node){
    if ($node->bundle() == "article") { // Content type check
        $image = file_create_url($node->field_image->entity->getFileUri()); // Creating file path from uri
        $variables['article'] = true; // Setting value true for current node is articles.
        $variables['background_img'] = $image;
    }
  }
}

and I try to get the image back with the following code in the field--node--field-image--article.html.twig template

but it doesn't work.

Can someone tell me what's wrong with this code? I would really appreciate it. Thank you.

Contrib module

What you are describing can be done easily with a contrib module. You could try background_image, bg_image_formatter, bg_img_field perhaps there are others.

Use image in node.html.twig or variant

If you MUST DO IT WITH CUSTOM CODE and you want my_image in node.html.twig or node--article.html.twig you need to prepare it in hook_preprocess_node

function THEMENAME_preprocess_node(&$variables) {
    $node = $variables["node"];
    if ($node->hasField('field_image')) {
      $variables["my_image"] = file_create_url($node->field_image->entity->getFileUri());
      // can set more variables
    }
}

Use image in page.html.twig

If you want to include it in a div inside your page.html.twig you should use hook_preprocess_page and note that $node has to be extracted from the ROUTE

function THEMENAME_preprocess_page(&$variables) {
  // get the current node
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {
    if ($node->bundle() == "article" && $node->hasField('field_image')) {
      $variables["my_image"] = file_create_url($node->field_image->entity->getFileUri());
      // can set more variables
    }
  }
}

Use image in field.html.twig or variant

I can't see the use case but if you want to use it in field.html.twig or a variant such as field--node--field-image--article.html.twig you can access it directly

{% set my_image = file_url(element['#object'].field_image.0.entity.uri.value) %}

or can set my_image using a hook_preprocess_field

function THEMENAME_preprocess_field(&$variables) {
  if($variables["element"]["#field_name"] == "field_image"){
    // get parent node
    $node = $variables['element']['#object'];
    if ($node->bundle() == "article" && $node->hasField('field_image')) {
      $variables["my_image"] = file_create_url($node->field_image->entity->getFileUri());
    }
}


what should I use as placeholder for a html img element? To keep it simple I've left some out of my img field.
here's my code:

$markup = t("", $img_src);

I've tried format_string() but that also retuns:

<img src="path/to/image">

It would probably be better to use the theme_image() function for that:

$image_html = theme('image', array(
  'path' => $img_src,
  'alt' => 'Some alt',
  // etc
));

If you're hell bent on using t() then you need to use it with the ! prefix, so the value is passed through without any checks/sanitisation:

$markup = t("<img src='!src' />", array('!src' => $img_src));

The docs for format_string() explains the different kinds of placeholders you can use, and which prefix you should use for each.


How do I replace a string when using hook_node_view()? I am trying to use hook_node_view() to replace, in the front page, <div>:placeholder1:</div> with the content of $string.

function mymodule_node_view(&$node, $view_mode, $langcode){
  $string = "I am here";
  $node->field_column_second['und'][0]['value']['#markup'] = array(
     '#markup' => str_replace(':placeholder1:', $string, $node->field_column_second['und'][0]['value'])
);

I also cleared Drupal cache, but I don't see any change.

What am I doing wrong?

According to the doc, the first parameter should be $node, rather than &$node.
The replacement code should look something like this:
$node->content['body'][0]['#markup'] = str_replace($old, $new, $subject); so you missed [0] in your code, when in doubt, do a dsm($node) and check the variable you want.
Complete code:

function test_node_view($node, $view_mode, $langcode){
    if (drupal_is_front_page()) { // check if necessary
    $string = "new";
    $node->content['body'][0]['#markup'] = str_replace('old', $string, $node->content['body'][0]['#markup']);
    }
    //dsm($node);
}


Migration from Joomla I am going to start work on a website that is already developed in Joomla 1.5
What are the possible ways to migrate the contents from Joomla.

PS: I have looked into joomla module but no luck!

Any ideas will highly be appreciated!

I've used Feeds and Menu Export/Import to migrate Joomla sites to Drupal a few times. It's a little tedious but it works.

I think the next time I have to migrate  Joomla site to Drupal I will use the Joomla to Drupal module. It doesn't appear to be regularly updated but looks like it should work for Joomla 1.5 and less. I don't think it will be useful for Joomla 2.x and up though.


Copy content from Word and use paragraph style names as classes Is it possible to copy content from a Microsoft Word document into Drupal and use the name of paragraph styles used in word as class names in the HTML?

I am using:

Drupal 7.34
CKEditor 7.x-1.15+1-dev

If I drag-and-drop content from Word into CKEditor the paragraph styles are used as class names which is good, but unwanted XML comes over from Word too. Example:

Prefixes<o:p></o:p>

A paragraph here with the normal paragraph style to test that class comes along:<o:p></o:p>

•&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; These are my own bullets<o:p></o:p>

•&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; To test if the HTML<o:p></o:p>

CKEditor Editor will not work the same way as Word so when you copy and paste some document to CKEditor. CKEditor will change the setting based on it own setting


Caching issue with class extension of RulesDataUI In my custom module I am trying to extend RulesDataUI class as below in the code which works fine just after clearing the caches, but on the next page reload I get warning as "Warning: class_implements(): Class RulesDataUICheckboxes does not exist and could not be loaded". I am not getting a clue how the class functions are invoked only just after cache clear.

The below code is present in my module name.rules.inc(nodequeue_rules.rules.inc)

 function nodequeue_rules_rules_data_info() {
      $return = array(
        'checkboxes' => array(
          'label' => t('checkboxes'),
          'ui class' => 'RulesDataUICheckboxes',
          'token type' => 'rules_text',
        )
      );
      return $return;
    }

class RulesDataUICheckboxes extends RulesDataUI implements RulesDataDirectInputFormInterface {
  public static function getDefaultMode() {
    dpm("hi");
    return 'input';
  }
  public static function inputForm($name, $info, $settings, RulesPlugin $element) {
    dpm("called");
    if (!empty($info['options list'])) {
      // Make sure the .rules.inc of the providing module is included as the
      // options list callback may reside there.
      $element->call('loadBasicInclude');
      $form[$name] = array(
        '#type' => 'checkboxes',
        '#options' => call_user_func($info['options list'], $element, $name),
      );
    }
    else {
      $form[$name] = array(
        '#type' => 'textarea',
      );
      RulesDataInputEvaluator::attachForm($form, $settings, $info, $element->availableVariables());
    }
        $settings += array($name => isset($info['default value']) ? $info['default value'] : NULL);
    $form[$name] += array(
      '#title' => t('Value'),
      '#default_value' => $settings[$name],
      '#required' => empty($info['optional']),
      '#after_build' => array('rules_ui_element_fix_empty_after_build'),
      '#rows' => 3,
    );
    return $form;
  }
    public static function render($value) {
    return array(
      'content' => array('#markup' => check_plain($value)),
      '#attributes' => array('class' => array('rules-parameter-text')),
    );
  }
}

I think you need to add your rules.inc file to the info files[] array to ensure that the file is included while rebuilding the UI.

See more related: https://www.drupal.org/node/1275958 & https://www.drupal.org/node/1276606


Issue a html.tpl.php override from a module? Is there a way to override the output of a page from a contributed module and issue your own html.tpl.php, effectively taking control of the output from the theme?

I want to do this in effort to create a unique login/registration experience, but can only seem to override the page level template, not the html level template. I see that the print module kind of does this, but is that the way to approach it?

According to this answer, you could simply print the page content in the menu page callback rather than returning it.

  To get data from Drupal's database and/or produced in PHP, you need a
  page callback (in a custom module) that output the data without the
  full layout rendering. This is easily doable by printing the content
  of the page directly in your page callback instead of returning it.

I guess the Print module implemented the printer-friendly page in this way. The following is the code snippet from the module.

function print_menu() {
  $items = array();

  $items[PRINT_PATH] = array(
    'title' => 'Printer-friendly',
    'page callback' => 'print_controller_html',
    'access arguments' => array('access print'),
    'type' => MENU_CALLBACK,
    'file' => 'print.pages.inc',
  );
  ........
}

/**
 * Generate an HTML version of the printer-friendly page
 *
 * @see print_controller()
 */
function print_controller_html() {
  $args = func_get_args();
  $path = filter_xss(implode('/', $args));
  $cid = isset($_GET['comment']) ? (int)$_GET['comment'] : NULL;

  // Handle the query
  $query = $_GET;
  unset($query['q']);

  $print = print_controller($path, $query, $cid, PRINT_HTML_FORMAT);
  if ($print !== FALSE) {
    $node = $print['node'];
    $html = theme('print', array('print' => $print, 'type' => PRINT_HTML_FORMAT, 'node' => $node));
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
    drupal_send_headers();
    print $html;
    ......
}

According to this, the module uses the custom HTML template print.tpl.php. It is a HTML-level template. The module then gets the HTML by calling theme('print',...) and render it directly to the browser using print $html;.

Here is a general idea for your purpose: mymodule.module

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();
  $items['mylogin'] = array(
    'title' => 'Custom Login Page',
    'page callback' => 'mymodule_custom_login_page',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );

  return $items;
}
/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return array(
    'mylogin' => array(
      'variables' => array('page' => array()),
      'template' => 'mylogin', // mylogin.tpl.php in your module folder
    ),
  );
}
/**
 * Generate a custom login page
 * @see more in print_controller_html() in print.pages.inc of the Print module
 */
function mymodule_custom_login_page(){
    $page = _mymodule_login_page_prerequisite(); // get/prepare necessary variables, js, css for the page
    $page['form'] = drupal_render(drupal_get_form('user_login')); // get login form
    // prepare html in mylogin.tpl.php
    // See more in print.tpl.php() in the Print module
    $html = theme('mylogin', array('page' => $page));

    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
    drupal_send_headers();
    print $html; // cease Drupal page rendering and render directly to the browser
}
/**
 * Prepare the array for the template with common details
 * @see more _print_var_generator() in print.pages.inc of the Print module
 */
function _mymodule_login_page_prerequisite(){
    global $base_url, $language;
    $page = array();
    $page['language']   = $language->language;
    $page['head']       = drupal_get_html_head();
    $page['title']      = '';
    $page['scripts']    = drupal_get_js();
    $page['favicon']    = '';
    // if there is a custom css file for this page
    // drupal_add_css(drupal_get_path('module', 'mymodule') . '/css/mylogin.css');
    $page['css'] = drupal_get_css();
    $page['message'] = drupal_get_messages();
    $page['footer_scripts'] = drupal_get_js('footer');

    return $page;
}

Template: mylogin.tpl.php

<?php
/**
 * @file
 * Custom login page template
 *
 * @ingroup page
 */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="<?php print $page['language']; ?>" xml:lang="<?php print $page['language']; ?>">

    <?php print $page['head']; ?>
    <title><?php print $page['title']; ?></title>
    <?php print $page['scripts']; ?>
    <?php print $page['favicon']; ?>
    <?php print $page['css']; ?>

This is custom login page.

    <?php
    if (!empty($page['message'])):
        foreach($page['message'] as $type => $message):
        ?>
            <div class="messages <?php print $type; ?>">

                <?php foreach($message as $msg): ?>

<?php print $msg; ?>

                <?php endforeach; ?>

        <?php
        endforeach;
    endif; ?>

<?php print $page['form']; ?>

    <?php print $page['footer_scripts']; ?>

I hope this will customize your login page as you need.


Problems with aggregated CSS I activated aggregate CSS on my local development and on a remote testing environment without any problems. Now on staging the aggregation of CSS files causes trouble: on some pages the styling looks correct but on random pages it is completely broken. The HTML sometimes shows:

<link rel="stylesheet" href="/?p0upgh" media="all" />
<link rel="stylesheet" href="/?p0upgh" media="all" />
<link rel="stylesheet" href="/?p0upgh" media="print" />

Sometimes some of the aggregated files seems not to be inserted via HTML meaning: there are no  Tags or just one - some of the stylesheets are missing.

I checked folder permissions: sites/default/files and sites/default/files/css have 777 as chmod values. The owner and the group of the folders and files belong to the correct folder and CSS are aggregated in sites/default/files/css.

Does anyone has some hint for me what my cause this problem?

The issue was connected to this: https://www.drupal.org/project/paragraphs/issues/2914259

I am not quite sure what exactly was the problem but when I went to the status report page I realized the error message

Entity/field definitions
Mismatched entity and/or field definitions
The following changes were detected in the entity type and field definitions.
Paragraph

- The Published field needs to be updated.

I implemented the update function

_update_function() {
  try {
    $entityUpdateManager = \Drupal::service('entity.definition_update_manager');
    $entityUpdateManager->applyUpdates();
  }
  catch (EntityStorageException $e) {
    print_r($e);
  }
}

run update and the problems with the aggregated css disappeared.


Maintaining the integrity of URLs while moving pages between site sections in Drupal 7 Could anyone please tell me how does drupal 7 handle urls when moving or reordering the pages within and between the sections witithin the site. Is it possible to preserve the urls or not?

If you are referring to the normal url, like node/3, then the url is always the same.

If you are referring to the path alias, which is the pretty url you can give to a page, or configure to generate automatically with tokens via the pathauto module, then when you move a node in to a different section the alias can change (this depends on how you have the alias generation configured, for example if there is nothing related to the section in the path alias then there will be no affect).

If your alias changes when you change a node, then normally the old path will no longer work and you can end up with people linking to those pages having their links break.

A workaround for this is to use the redirect module.

If you have pathauto and redirect both installed, then on the pathauto settings page you can configure the "Update action" option to create a redirect between the old and the new alias when a node is updated. This will stop incoming links from breaking when you change a node and its alias changes.

I would also recommend configuring the redirect module to delete old redirects if they haven't been used for a period of time (say 4 months for example).
This means if no one has used the old path in 4 months then it will delete the redirect as you likely don't need it anymore. Set the period to whatever you feel comfortable with.

I recommend not using this auto-redirect on alias change feature during development if content is likely to change a lot. This is because you end up with a lot of redirects that are not needed and if you change a node so that the alias changes from alias1 to alias2 and then back to alias1 again, you can get errors. If you care to learn more about those errors, see:

http://drupal.org/node/1817976
http://drupal.org/node/1263832
http://drupal.org/node/1796596


How to get Panels to override node with "no extras" I'm having a problem with the node/%node use of Panels. I would like to display the body content of a node in one pane and all the extra fields which I have added into the content type in another.

The problem I'm hitting is the "no extras" option in the Pane settings makes no difference - all the fields (body and extra fields) are always displayed.

Searching around the web, nobody else seems to have this issue. Since it is what panels is supposed to be good at, I think I'm missing something. I've tried using the panels wizard and doing this manually. I had it working in Panels 1 in D5 :(

I'm using D7 and Panels 3.

Any suggestions gratefully received!

Edward

The problem is (I think) that when you added content (Whichever Variant -> Content -> Gear -> add content) you clicked Node and then Node content.  Node Content will display all of the content of the node (Title, Body, and all Fields).  If you just want to display the body choose Node body.

Then in another Pane (Panel Biggest -> Region -> Pane Smallest) you can add your other fields.

Here's a video that talks about Panels and Panels Everywhere and can help show this in action.

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

Hope this helps!


How to use use db_rewrite_sql() with db_query() in D7? I read article where it was written to use db_rewrite_sql($query). In Drupal 7, you need to use addTag('node_access') along with `db_select().

I have  a query with 8 columns and 4 conditions; for simplicity I am using db_query().

How can I use db_rewrite_sql() with db_query()?

You have to use db_select() with the addTag() modifier.

The query you mention doesn't sound too crazy so it should be fine for db_select().
The only downside is it can be a bit slower.

As per the db_query() api docs:

  Use this function for SELECT queries if it is just a simple query string. If the caller or other modules need to change the query, use db_select() instead.


urol executed via bash throws exception error if role has a space in it Role name "teaching assistant"

command executed is:

drush @comply-all urol "teaching assistant" sdf --y

if I copy and paste this it works fine. if the following command is called from a bash script it bricks every time when encapsulating the role name (which is needed otherwise it's evaluated by drush as two different arguments). Anyone experience anything similar?

[ulmusdrush@localhost ~]$ exception 'Drush\Role\RoleException' with message 'Could not find the role: "teaching' in          [error]
/home/ulmusdrush/.composer/vendor/drush/drush/lib/Drush/Role/RoleBase.php:46
Stack trace:
#0 [internal function]: Drush\Role\RoleBase->__construct('"teaching')
#1 /home/ulmusdrush/.composer/vendor/drush/drush/includes/drush.inc(113):
ReflectionClass->newInstanceArgs(Array)
#2 /home/ulmusdrush/.composer/vendor/drush/drush/commands/core/role.drush.inc(273):
drush_get_class('Drush\\Role\\Role', Array)
#3 /home/ulmusdrush/.composer/vendor/drush/drush/commands/user/user.drush.inc(281):
drush_role_get_class('"teaching')
#4 [internal function]: drush_user_add_role('"teaching', 'assistant"', 'qwe')
#5 /home/ulmusdrush/.composer/vendor/drush/drush/includes/command.inc(359):
call_user_func_array('drush_user_add_...', Array)
#6 /home/ulmusdrush/.composer/vendor/drush/drush/includes/command.inc(210):
_drush_invoke_hooks(Array, Array)
#7 [internal function]: drush_command('"teaching', 'assistant"', 'qwe')
#8 /home/ulmusdrush/.composer/vendor/drush/drush/includes/command.inc(178):
call_user_func_array('drush_command', Array)
#9 /home/ulmusdrush/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(62):
drush_dispatch(Array)
#10 /home/ulmusdrush/.composer/vendor/drush/drush/drush.php(70):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#11 /home/ulmusdrush/.composer/vendor/drush/drush/drush.php(11): drush_main()
#12 {main}

Use

drush @comply-all urol "teaching\ assistant" sdf --y

Might be helpful to you.


Trouble with form api I got a problem to toggle the textfield if the ckeckbox with value 1 is checked.

function gkform_nameform() {
 $form['check'] = array
    (
    '#type'            => 'checkboxes',
    '#options'         => array
      (
      1 => 'Sometext',
      2 => 'Sometext2',
      ),
    );
$form['user_name'] = array(
'#type'=>'textfield',
'#states'=>array(
    'visible'=>array(
    ':input[name="check"]'=>array('checked'=> 'options' => '1' == TRUE),
    ),
  ),
 );

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

The Form API gives checkboxes names that include their options key. So your :input needs to be slightly adjusted to

':input[name="check[1]"]' => array('checked' => TRUE),


Auto Increment value for field collection I have a field collection group to which I am importing values using Field Collection Feeds Importer. This requires a unique identifier field within the field collection. This has posed an issue where the user has to keep track of these identifier fields. One way to avoid this is having an auto increment field so that when a new row is added it automatically auto increments this field without any user interaction. This would also help maintain the correct sequence at all times and avoid any user editing accidental mistakes.

This is how it is right now

Any ideas or existing functionality to use this.

Thanks.

The Serial Field module should be able to do that:

  This module provides an auto-increment (serial) field.

  Unlike Drupal's built-in auto-increment node ID, which is global and
  shared by nodes belonging to all content types, serial fields are
  managed per content type (D6) / entity (D7). For example, the serial
  field of an Invoice instance will generate a unique sequential number
  (starting at 1, then 2, etc.) exclusively for Invoice instances.


Creating "Welcome " special menu items I want to create special menu items with title "Welcome ". I want to make it as special menu item (without link to any node), that shows sub-menu on hover. For that I have used Special Menu Items module and is working fine.

But I am not able to figure out how to create dynamic menu title in form
"Welcome Username".  I have tried using Menu Token module as well, but it didn't work. It just displays token as it is.

Any suggestion how can I achieve this using module or programatically.

-- Many thanks for your time.

I used this on www.grupposportivo.be in a bootstrap nav bar

<?php global $user; if ($user->uid != 0)
                { print '
' .t('').
                    'uid). '">' .$user->name. '

'; print '

                    ' .t('Logout'). '

'; } else { print '

                    ' .t('Login'). '

'; print '

                    ' .t(''). '

'; } ?>


Facet block with dynamic title Is there a way to dynamically change the facet block title on each page based on the field label of the specific content type? The same field has different labels in each content type.

For example if we have in ‘Content type 1’ a field with Machine name: field_1 and label ‘AA’ and the same field in ‘Content type 2’ with label ‘BB’ when we are on Content type 1 page the facet block mast show AA and when we are on Content type 2 page it mast show BB.

I found a way to change the title with CSS using the Code per Node module, but it is not automatic and I have to insert the code in each content type. It doesn't seem to be right. There must be a better way.

I use this CSS in each content type.

.block-facetapi-”THEBLOCKID” .block-title {
  visibility: hidden;}
.block-facetapi-”THEBLOCKID” .block-title::after {
  content: 'Label B';
  visibility: visible;}

You could change the block title in your theme or module using the theme function or theme preprocess function.

For example:

/**
 * Implements hook_preprocess_facetapi_title
 */
function HOOK_preprocess_facetapi_title(&$variables) {
  $some_condition = TRUE;
  // If some condition
  if ($some_condition) {
    // Some title..
    $title = t('Custom title');
    // Set theme/template variable for title
    $variables['title'] = $title;
  }
}

See also: theme_facetapi_title


Custom Javascript Not Loading On Paginated Pages (Except First Page) I am running the following jQuery that affects elements on a page view.

$(document).ready(function($){
    $(".views-field-field-video").click(function() {
        $(this).parent().find("a.cboxElement").click();
    });
});

The code works perfectly, but only on the first page. When I use the pager at the bottom and navigate to any other page, the script does not work. Then, when I navigate back to the first page, the script also fails.

If I reload the page however, it brings me back to the first page and the script works again.

EDIT: The classes I am selecting in the script remains the same on all pages.

The problem is when using ajax pagination in the view, document.ready isn't called.

Instead you should follow best practice and use Drupal.behaviors instead.

That way, the behavior will run on document.ready and on the ajax refresh.

Try this:

(function ($) {

  Drupal.behaviors.cboxClick = {
    attach: function (context, settings) {
      $(".views-field-field-video").click(function() {
        $(this).parent().find("a.cboxElement").click();
      });
    }
  };

})(jQuery);


View, Nodes categorized by field with counter just right to Category name I would like to split my 100 nodes by category field and display amount of nodes (from 1 category) near Category name.

Here is a screenshot of what I want to get at the end.

  (X documents)

Could you please give me a hint/direction how can I do that?

"X" - number of documents in category
"documents" - word that could be translated in other languages.

Amend your view as follows:

Add the category term as a field to the view, either straight as a field from the node, or as a relationship. Make sure to exclude this category field from display.

Choose your format for the view, and for the format settings, select the hidden category field you just added as 'Grouping Field Nr. 1'.

Your view should now categorise the content with the category as the headings for each group.

Now to add the count.

In the Advanced part of the view, click on Theme: Information.

This open this window:

Now copy the name of a view override from the row 'Style Output' (underlined in red in screenshot'. The names to the left are to override the view in a very general way, and more the right it will target the view more specifically. Make it specific so that only this view is targeted.

Create a new file in your theme's templates folder with the name you just copied.

Paste this code in your file (it comes from clicking on the blue 'Style output' link in the view's theme information window, with a slight adaption).

<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>

<?php print $title . ' (' . count($rows) . ' ' . format_plural(count($rows), 'document', 'documents') . ')'; ?>

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

<?php endforeach; ?>

The last thing to do is to clear your cache.


How to programmatically import a block to existing view? I need to programmatically import a block to existing view with its settings.

I know how to export the whole view and import it programmatically. But I don't want to export whole view and then import whole view. In my view there is 25 blocks, so it gives me 4000 lines of code to import.
I can copy export code only of my new block. But how to import only this part of code to the existing view? Is that possible? I can't find any solutions.

The indicated "block" you point out in the UI, is internally called a "display". Displays are stored inside the view object in the display property (e.g. $view->display).
If you look at the views export code you should see the pattern of exported blocks (e.g. /* Display: Block 1 */, /* Display: Block 2 */, etc.) that's rendered by the views::export() method.
For each block (i.e. display) you should see the $handler = $view->new_display(...) followed by many $handler->display... lines that add the relevant fields/filters for that display.
To programmatically import a single display you would do something like the following:
$view = views_get_view('my_existing_view');
// @TODO: Add my new display handler code
$view->save();


Commerce-Marketplace : Members tab in store's page doesn't show up After this clean install :

Drupal 7.28
Commerce 7.x-1.9
Commerce-Marketplace 7.x-1.0-beta2 (same issue with current dev version)
ECK 7.x-2.0-rc3+15-dev

I create a new store but can't see the "Members" tab as seen on the demo site (I also tried the direct URL "commerce_store/store/{ID}/people", no error but I stay on store page).

Here is a screenshot

And the demo site

Do I miss a step to activate the store members management tab/pages ?

Thanks for your help or direction to solve this.

Problem resolved after this update : https://www.drupal.org/node/2284457#comment-8962135


Multiple REST endpoints I have an endpoint, which is active and working for more than a year, and I recently had the need to add a new endpoint, which obviously has a different url ("Path to endpoint").

For both, however, I need to use the login functionality, and other custom actions (each one has its own url, callback and access callback, in two separated custom modules).

But on every call, i can see that both endpoints are being requested, all arguments are being doubled etc. Here's the $controller as seen from hook_services_request_preprocess_alter:

Array
(
    [help] => Array
        (
            [0] => Description from endpoint 1
            [1] => Description from endpoint 2
        )

    [callback] => Array
        (
            [0] => MY_FIRST_MODULE_callback_function
            [1] => MY_SECOND_MODULE_callback_function
        )

    [access callback] => Array
        (
            [0] => MY_FIRST_MODULE_access_callback_function
            [1] => MY_SECOND_MODULE_access_callback_function
        )

    [args] => Array
        (
            [0] => Array
                (
                    [name] => email
                    [type] => string
                    [description] => Email
                    [source] => Array
                        (
                            [data] => email
                        )

                    [optional] => 1
                )

            [1] => Array
                (
                    [name] => email
                    [type] => string
                    [description] => Email
                    [source] => Array
                        (
                            [data] => email
                        )

                    [optional] => 1
                )

        )

    [etc] => ....

)

This happens whichever url is requested, it's causing both the iOS and Android apps to crash, and i couldn't find a way around it.

What should / can I do to run both endpoint independently, and why are both getting invoked even if the url ("Path to endpoint") is different?

Use a distinct resource name, or simply enable the same resource on the other services endpoint to use it there.

To debug issues with the controller, you can check in RESTServer.inc in particular the functions getController and resolveController. Adding some debug/logging code there may help to resolve the issue.


Content export and import / content deployment It's easy to deploy configuration of content types, views and so on...

What are the options for deployment of content (nodes) between different environments?

The Default Content module uses cores REST/HAL/Serialisation API's to export content to JSON. You put the content into you_module/content/[entity_type]/anything.json and the content is automatically imported when you enable your module.


How do I use $form_state['storage']['my_key']? The question is clear from the title itself .

I looked in the api specified in :  https://www.drupal.org/node/2310411 .

But it only mention to convert

$storage = &$form_state['storage'];
$form_state['storage'] = &$storage;

to

 $storage = &$form_state->getStorage();
 $form_state->setStorage($storage);

But not a key in the $form_state['storage'] ? any help is appreciated .

The example in the documentation link seemed to cause confusion.  Simply set your values in an associative array and use set/get storage.

$vals = [
  'name' => 'bob',
  'age' => 50
];

// save the data.
$form_state->setStorage($vals);

// retrieve the data
$vals = $form_state->getStorage();
$str = $vals['name'] . ' is ' . $vals['age'] . ' years old.';

https://www.cyberdev.co/how-to-store-temp-form-state-data


How could I select all the authenticated users and just only them? I've a long running Drupal 7 site. Now my client needs a way to select (and act upon) the users who are not in the role "A" and "B", but just "Authenticated Users".

I know that the latter are not in the users_roles table which makes the standard admin/people form and the advanced users module useless (they both skip over the Authenticated Users).

Do you know of any module that could do something like that? Unfortunately it seems there is no way to alter the query in the user.module (which joins users_roles) so I feel like it's a dead end. Should I need to write a module with a form and duplicate most of the features of the admin/people?

Using the Views Bulk Operations (VBO) module it is possible, by creating a view to select all the people not in the desired roles.


how to change save button to Save and keep published? In the content form want to change the  publish checkbox and save button into the dropdown "Save and keep published" and Save and unpublish
How can i change the layout for all content type.

This looks like you want to change the node edit form back to the old layout of Drupal 8.3. You can use this module:

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


Inserting in user's field on creating the user? I need to add subscription key field to user as a hash of his email and time created so I did this in a custom module

function custom_newsletter_mail_entity_presave($entity, $type) {

    if($type == 'user') {
        if(empty($entity->get('field_subscription_key')->getValue()[0]['value'])) {
            $hash_input = $entity->getEmail() . $entity->getCreatedTime();
            $key = hash ('sha256' , $hash_input , FALSE);
            $entity->set('field_subscription_key',$key);
            // $entity->save();
        }
    }
}

This is not working for some reason, note that I tried this outside of module on all users array and it worked. for some reason, the subscription key field is still empty, the second if condition is there to prevent the field from being overwritten.

If you're using Drupal 8,
See This one.

Update a node:

Example 1 : Update title

$node = \Drupal\node\Entity\Node::load($nid);
$node->setTitle('The new Title')
$node->save();

Example 2 : Update a field ('body' and 'field_name')

$node = \Drupal\node\Entity\Node::load($nid);
$node->set("body", 'New body text');
$node->set("field_name", 'New value');
$node->save();

To make changes after click on save / edit button, you can use the hook_entity_presave.
hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity);

Example:

function CUSTOM_MODULE_node_presave(Drupal\node\NodeInterface $node) {
  $node->setTitle('Edited Title');
  $node->set('body', 'this is the bew body');
  //CAUTION : Do not save here, because it's automatic.
}

  Note : Do not re save inside of hook_entity_presave().

Using HOOK_entity_presave()

function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityType()->id() == 'node') {
    $entity->setTitle('The new Title');
    //CAUTION : Do not save here, because it's automatic.
  }
}

Source : drupal8.ovh


Is there a way to get multiple image sizes from a single image? In Drupal 8 Manage display for the image field, I can assign only one image style.

I have two image styles: thumbnail and medium.

when I upload an image through image uploader, I need to view my uploaded image in those two image styles.

Is there a way to show the image in those two sizes from the single image I have uploaded?

If I selected thumbnail in the manage display on the image field it will save the image as thumbnail, but not as medium size as well. I need to save the image
 in both the sizes, or I need to get both the styled images from the single image I upload. The following code can get the image for the given style in manage display.

$imageStyle = ImageStyle::load('medium');
$galleryImage = $imageStyle->buildUri($image->entity->getFileUri());

By default, any file you upload via the file field goes into the public files directory /sites/default/files. And you can choose to apply any image style to the same image and configure it separately per display.

E.g. Let's say you upload an image with name my_beatiful_cat.jpg from a file field on a node page.

The image by default will stay at sites/default/files/my_beatiful_cat.jpg.
From manage display of the content type, in the default view, let's say you choose the image style to be medium and save.
When you view the node, a new image will be created from the uploaded image at sites/default/files/styles/medium/public. So, you will have a file sites/default/files/styles/medium/public/my_beatiful_cat.jpg which will have the dimensions as per the image style applied.
This is true for any other image style that you apply for any other display.

So, you only upload an image once. Image styles are responsible for generating images with respective sizes as per the configuration and the appropriate image file is rendered.


What's this strange error during entity_creation? I'm trying to create a (no bundle) entity from a feed using entity API, but I keep running into strange issue. The code for the entities is this:

function my_entity_provision() {
  $a = entity_create('entityType', array(
    'pid' => NULL,
    'aid' => 1,
    ...

  ))->save();
}

But when running it I run into these errors:

Warning: class_implements() [function.class-implements]: object or string expected in entity_create() (line 420 of ...../sites/all/modules/entity/entity.module).
Warning: in_array() expects parameter 2 to be array, boolean given in entity_create() (line 420 of ...../sites/all/modules/entity/entity.module).

I've tried looking on drupal and drupalcontrib for the correct implementation, but all code blocks show no text? :s

My code looks similar to Create Entity Programmatically in Drupal which does seem to work. (Since I have no bundle, I didn't define the type in the array, I read somewhere it can be omitted . But that made no difference anyway).

My entity info is as follows:

/**
 * Implements hook_entity_info().
 */
function my_entity_entity_info() {
  $return = array(
    'entityType' => array(
      'label' => t('entityType'),
      'controller class' => 'EntityAPIController',
      'base table' => 'entityTypes',
      'fieldable' => FALSE,
      'entity keys' => array(
        'id' => 'pid',
      ),
      'static cache' => TRUE,
      'view modes' => array(
        'full' => array(
          'label' => t('Full Entity'),
        ),
      ),
      'views controller class' => 'EntityDefaultViewsController',
    ),
  );

  return $return;
}

Argh, it seems the two different entity modules (core & contrib) have confused me once again.

The EntityAPIController I chose as controller class has no method save(). It uses entity_save($entity_type, $entity); instead.

So the function had to be:

function my_entity_provision() {
  $a = entity_create('entityType', array(
    'pid' => NULL,
    'aid' => 1,
    ...

  ));
  entity_save('entityType', $a);
}