What is the difference between a Drupal session variable and a cookie? When you set a Drupal session variable (i.e. a "magic" variable you may set like this):

$_SESSION['mymodule'] = array('key' => 'value');

the value goes away when the user logs out.

If you set a cookie, using the function

user_cookie_save(array('key'=>'value'))

the value saved survives the user session.

However, I wonder if they just two of a kind (i.e. a Drupal session variable is just a cookie, but with the lifetime restricted to the duration of a the session.

Or is a Drupal session variable not implemented using a session cookie?

Seeing this has two votes, I'll try to explain it.

Drupal uses the built-in PHP session mechanism, which as you rightly suspect is based on a cookie. The cookie name is SESS followed by a long string of characters, and its value is another long string of characters. PHP detects this cookie and makes it available to Drupal's session implementation, which by default uses the database table sessions for storage, with the value of the cookie as the key sid.

The session entry also records the user ID: early in the Drupal bootstrap sequence the session is loaded and then the corresponding user object, which is subsequently used to govern access to resources, based on the user's roles and other attributes.

Data stored in the PHP global array $_SESSION is automatically saved to the current session's database entry by Drupal at the end of a page request. This is typically used to store relatively transient data such as items in a shopping cart.

Other cookies can be saved and retrieved in code (including JavaScript) and they will not be affected by logout unless you specifically write code to delete them when that happens. Confusingly, cookies with an expiry time of 0 are also often termed "session cookies" - these are deleted when you shut down your browser.

There's a lot more that could be said and I'll add some good references when I have a chance.


How can I replace the hyphens in front of child terms with something else? What code is responsible for adding - in front of taxonomy term sublevels on a taxonomy field in a node edit form?

Even though the most non-intrusive way to override it is preferred, I'm comfortable even with core patches.

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

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


Filter menu_tree_all_data() tree by language? My site uses multiple languages and I'm using menu_tree_all_data() to get the menu tree programmatically. Currently all nodes and their translated nodes use the same menu tree.

If I use a menu block the menu that is displayed is filted by language version of the site the user is on. Which is good.

When calling the menu_tree_all_data() in code to build a menu programmatically it returns the entire tree and there does not seem to be an option to filter the menu by a language.

Does anyone know how to get the menu tree in code filted for a specific language?

I suppose you have i18n_menu.module installed. In this case, use i18n_menu_localize_tree($MENU_TREE) to get the tree for the current language.

To get secondary menu, for instance (on template.php):

$tree = menu_tree_all_data('menu-secondary');
$variables['secondary_menu_expanded'] = menu_tree_output(i18n_menu_localize_tree($tree));


How can I use Typekit fonts with Drupal 6? Preferably without an extra module I need to use some fonts from Typekit on the site I'm working on. Without the help of an extra module would be the best solution.

I have two lines to go in the  of page.tpl.php that call scripts.(< script >< /script >)

Should I put them in /themes/mytheme/template.php ? If so how, can you give me an example of what the code should look like?

Can I just put the call for the scripts right in the page.tpl.php file? with drupal_add_js ?

Anything else I should know?

Helpful links would be cool too. I got a bunch from #drupal on IRC today but none pinpointed it enough for me.

Thanks

Drupal 6

If you want the typekit code on every page of your site and you don't want a complicated solution just put the code in the page.tpl.php file. They are external scripts I assume so drupal_add_js won't help you in D6.

You can add things to the scripts variable in template_preprocess_page(), but if you are going to do that on every page then you may as well just put it next to where the scripts are printed in page.tpl.php


WYSIWYG and TinyMCE stripping out float: left I've got the WYSIWYG module installed and the TinyMCE javascript library as well. I've created a text format "Rich Text" which is similar to Filtered HTML but I've added more allowed tags.

I insert an image into my text and I set it to align left which adds float: left to the markup. However, when I save and view the page, the float: left has been stripped out.

I can't find any options in the WYSIWYG configuration or my "Rich Text" format that allows me to control this. Am I missing it somewhere?

Why is my float: left getting stripped out?

My solution:

I downloaded a new module called WYSWIWYG Filter. On my Text Format, I turned off the Limit allowed HTML tags option and instead enabled the WYSIWYG Filter option. Then below in the WYSIWYG Filter settings, I configured the allowed HTML elements like so:

a[!href|target<_blank|title],
div[align<center?justify?left?right],
p[align<center?justify?left?right],
br,span,em,strong,cite,code,blockquote,ul,ol,li,dl,dt,dd,
img[!src|alt|title|style|width|height|typeof],
@[style|title]

And I checked all the boxes to allow margins, padding, floating, etc.


Problem in uploading an image to my drupal site My Drupal site contains images and videos of an event. I got a problem with image module. When I am uploading image an error "The file could not be uploaded" is displayed. I set the formats as jpg, jpeg, png.

I have a similar site in another server but it is free from this issue. It is uploading images smoothly.

How can I solve this?

You check the permissions on the sites/default/files folder. Using linux you could execute sudo chmod -R 755 <foldername> from your terminal.

A good idea could also be to check your log files in order to track down the error. For example if you are running apache you could check the /var/log/apache2/error_log to see what goes wrong.


DPM simpleXMLElement returns just the object but echo returns its value When I DPM the simpleXMLElementObject it returns

  (Object) SimpleXMLElement

print_r returns the following:

SimpleXMLElement Object ( [0] => c1e1c959-c99d-42f0-8a44-2998b )

Although when I echo I can see the value for my object. Thus what is the best way to get its value in a string format?

This way then I can process that information.

Thanks.

The issue was that dpm was not printing some of the SimpleXMLElement values. They were only visible from the var_dump after die. Maybe there is a better way to check these. What I noticed was the value was being generated but dpm was not showing it and var_dump did.


Show parent child relationship of taxonomy term in view I am looking for a way to display the list of taxonomy terms in a view indenting the child tax terms. I need to be able to see all Taxonomy terms including the ones that do not have children terms. any ideas?

Domain 1
    Sub-domain 1
    Sub-domain 2
Domain 2
    Sub-domain3
    Sub-domain4
Domain 3
Domain 4

I tried to follow the suggested solutions but they did not work out for me.  The first one in the link is asking you to provide a parent taxonomy term to filter by. I want to get the complete list.  the Second one only provide the Taxonomy terms that have a parent child relationship. I need to see all taxonomy terms even if they don't have children.  Here is the screenshot of my view setup, I followed the exact steps outlined by louieliu.  As you can see it only shows Environment with subchildren of Soil and Weather but does not show the other Domains without subchildren.

You can also try Views tree module.

Project page says

  This module provides a tree-based style plugin for Views. It is
  equivalent to the tree-based style template from Views 1.

  It is based off of the list style. Although it generates a nested
  view, there is still only a single query run for the view making it
  quite performant.

  Compatibility

  This module has been tested and used with the following
  relationship-oriented modules:

  Taxonomy (in core) - parent/child relationships


How to override default class of custom text field in views? How can I change the nothing in the "views-field-nothing" class of a custom text field in views?

I just can't find the appropriate setting...

Just found it myself. Sometimes you have to ask to look into something unexpected...

In style settings it's the "Customize field and label wrapper HTML" -settings i was looking for. With "create a css-class" you can override the default setting of the wrapper.

Thanks for looking anyway...


Bulk import images into content image field I've created a content type called "Products" wich has the following fields:

code (Product's id)
Title (Product's name)
Description
Image (Product's picture - image field)

I've imported a list of products from a CSV file using Feeds module. So far everything is ok. Except for the pictures.

Then I have a lot of pictures (3000+) that I need to do a bulk import into each product's image field.
The picture's files are named product_code.jpg, e.g.: 001.jpg being the image of the product 001, 002.jpg for the product 002... and so on.

I've searched for modules that could do this kind of import, but have found none.
I took a look at the database and I'm thinking about uploading the files to the server via FTP and alter the tables by hand, since the filenames = product's code.

What's the best method for me to do this kind of import? Is there any module I am missing?

Thanks!

Why don't you make a new csv field for the images with a relative path to each image as the row value? Then when you import the nodes using Feeds, the image field will automatically have a link the the image


How to avoid duplicate entries when changing the text inside t() function in Drupal 7 I am using t() function in modules and templates. But when I need to correct the original English text, I find that I have two rows in the database (I manage it through i18n translating interface manager). One is the original text and the other the corrected one. I delete the old one and translate the new one. Is this the standard procedure? Could there be a better way of translating, for example with a module based on numerical ID or something to avoid duplicate or obsolete strings?

I think there is not a better way, because all those strings are stored/returned in the database as the code is being read out.

I think there is no way to know if they are actually exists in code to be used or not.


Problem with content type permission I have a content type called: Activity. Then I have a role called: Gestor
In /admin/people/permissions I make sure I checked (for the Gestor role):

Activity: Create new content

Activity: Edit own content

Activity: Edit any content

Activity: Delete own content

Activity: Delete any content

Now I login with a Gestor user role and tried to go to /node/add/activity and I get ACCESS DENY

The content type has the defaults fields: body and title.

I already rebuild permission at: /admin/reports/status/rebuild but not working...

UPDATE
*If I check Bypass content access control I get access to fully manage ALL content type*

You probably have a content access module (e.g. Content Access) installed that's conflicting with the default access settings.


'File' class not found in submitForm(...) - uploading managed_file I have an image field in my custom module's form:

namespace Drupal\my_module\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Component\Utility\Html;

class MyModuleForm extends FormBase {

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['image_file'] = array(
      '#type' => 'managed_file',
      '#name' => 'image_file',
      '#title' => t('Block image'),
      '#size' => 40,
      '#description' => t("Image should be less than 400 pixels wide and in JPG format."),
      '#upload_location' => 'public://myimages/'
    );
...

And for submitForm(...) I use:

  public function submitForm(array &$form, FormStateInterface $form_state){
    $image = $form_state->getValue('image_file');
    $file = File::load( $image[0] );
    $file->setPermanent();
    $file->save();
    ...

But when I use the form to submit image I get error (in log):

  Error: Class 'Drupal\my_module\Form\File' not found in ...

You need to add it in a use statement in your class (at the top of the file with the rest of the use statements)

use Drupal\file\Entity\File;


How to remove custom block parent div's? I have created custom block in my custom module. I have created block template file into module templates folder. Custom block content coming successfully as per given in block__MODULENAME__dummmy_xyz.tpl.php file. I have only added following code into my block tpl file:

Hello

But it is coming with block parent div's, Block id and block-inner tag. I dont want to show those extra div's.
Following is the hook_theme which I have in my module file:

/*
 * Implements hook_theme().
 */
function MODULENAME_theme($existing, $type, $theme, $path) {

    $items = array();

    $items['MODULENAME_dummmy_xyz_block_theme'] = array(
        'type' => 'theme',
        'path' => drupal_get_path('module', 'MODULENAME') . '/templates',
        'template' => 'block__MODULENAME__dummmy_xyz',
        'variables'  => array()
    );
    return $items;
}

I am rendering block into tpl using,

$block = block_load('MODULENAME','dummmy_xyz');
print drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));

block.tpl.php code:

<?php print $outer_prefix . $inner_prefix; ?>
  <?php print render($title_prefix); ?>

  <?php if ($title): ?>
    <h2<?php print $title_attributes; ?>><?php print $title; ?>

  <?php endif; ?>

  <?php print $content_processed; ?>

  <?php print render($title_suffix); ?>
<?php print $inner_suffix . $outer_suffix; ?>

Kindly guide me.

_block_get_renderable_array function render default block theme where I couldn't remove parent element, So I made it by using module_invoke function:

$block = module_invoke('custom_module_name', 'block_view', 'block_name');
              print render($block['content']);


Cleaning a Drupal database from anything which is not nodes, taxonomy and other regularities? Assuming we have an all-core Drupal site; Is there a utility or even a Drush/Dconsole command to "clean" the database of anything which is not a node, or a taxonomy or any regular core-based data of all sorts ?

In other words, a utility or command to clean from the DB anything which is, for example, a remnant of a module that we installed and then deleted that is now stuck on the DB in several places and removing it manually can be sisiphyc and or tiresome (especially when you have several cases at once).

I don't think that this is possible because the core can not know what you need before you have it configured (fields, nodetypes etc).

You would need kind of a transaction checkpoint at the DB structure, and the possibility to rollback every structure manipulation and data therein that has happened after that point.

I usually have a system besides of my content staging system to test contributed modules. Copy content stage to dev, apply module on dev, test, rollback or move the module to content stage.

If you are the module dev yourself - make up your correct uninstalls :-)


Create link with node id parameter When I create a new content type, I want to prefill a link field following this format :

/my/specific/link?node_id=<CURRENT_NODE_ID>

Is it possible to access the node id before his creation? Or a specific id to refer to this new content type??

[EDIT]

More details :
I want to add a content type, which is a job offer. In this content type, there is a Link field, that refer to a web form to apply to the job offer. So I need to prefill the link field, with the node ID to know the job you are applying for.

You do not need a link field for that. You can generate link at theme level for example. Or even better in hook_node_view:

  The module may add elements to $node->content prior to rendering. This hook will be called after hook_view(). The structure of $node->content is a renderable array as expected by drupal_render().

Last but not least, if you really want it to be a field, use Computed Field and have it calculated at save.

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


How can I update or insert a row with NULL fields using query builder? In Drupal 7, I'm being sent an array of values from a user submission that are being mapped directly to a database table.

Some of those are blank and I'd like to set those fields to SQL-style NULL in the database.

To do this, my values array has the empty or blank fields set to PHP's NULL:

array('field1' => 'value1', 'field2' => NULL)

And I'm using db_update() like this:

$result = db_update('table_name')
  ->fields($record)
  ->condition('cmid', $form_state['values']['cmid'])
  ->execute();

However, db_update() doesn't appear to like NULL values in the $record array. I'm not seeing any sort of errors, unfortunately, except that no updates are being made to the database and that $result is returning a falsy value.

How should I be using db_insert() or db_update() if some my values may be blank at times, and I'd like these to equate to setting those respective database fields to NULL?

db_update() does allow NULL to be used for field values. To confirm this, check out the core table, block_custom, which allows both block_custom.body and block_custom.format to be NULL.

First, insert some dummy data either through the block administration screen or via SQL:

INSERT INTO block_custom (body, info, format)
  VALUES ('Lorem Ipsum', 'Test block', 'plain_text');

Now run the following code:

db_update('block_custom')
  ->fields(array('body' => NULL))
  ->condition('info', 'Test block')
  ->execute();

If you look at the table after executing, block_custom.body will be set to NULL.

db_insert() works too:

$fields = array(
  'body' => NULL,
  'info' => 'Test block 2',
  'format' => 'plain_text',
);

$result = db_insert('block_custom')
  ->fields($fields)
  ->execute();

So there's something else wrong with your statement. Two things to check:

Ensure $record really has NULL values in the db_update() query. var_dump() the array just before the db_update() and ensure nothing's modified the values.
Check the condition statement. If set to a condition that doesn't match any of the rows in the table, the update won't occur and $result will contain a falsy value. Since it's perfectly value to have an UPDATE query that matches no rows, it won't throw an exception or return an error.


Select form, write selected item to database I'm using Drupal 7 and Form API.

My Problem:

I want to load rows from my Database and put them in a Select Form(Form API). After this form is submitted I want to write the selected option in my database.

The first step works fine but I don't know how to get the selected option for writing it into my database.

Load values from database:

$result = db_select('color', 'c')
->fields('c', array('ID', 'color', 'name')

->execute()

foreach($result as $row) {
     $options = $row->color . ' ' .$row->name;
}

Add options to form:

 $form['colors'] = array(
   '#type' => 'select',
   '#options' => $options,
 );

When form is submited:

db_insert() //Add ID of selected item to database

How do I get the ID of the selected color? The options of this select form is a name combination(color+name)

First of all, there is a small error in your code, $options should be an array. Moreover, if you add a key=>value pair for each option, you can get the key of the selected option in the form_submit function. Here is what your foreach could look like:

foreach($result as $row) {
  $options[$row->ID] = $row->color . ' ' .$row->name;
}

and in your submit function you can grab the ID of the selected option like this:

$color_id = $form_state['values']['color'];

Good luck!


Skipping form validation with a custom action button Related to my previous question -- I've got the button added to the form properly (thanks googletorp!), but now I'm having separate validation issues beyond just adding the button.

I have added a "Cancel" button to my custom content entity add/edit form, using
hook_form_id_alter. When clicking this button I want it to leave the form completely and return to another admin-side page:

function mymodule_form_myform_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $form['actions']['cancel'] = array(
        '#type' => 'button',
        '#weight' => 10001,
        '#submit' => array('cancel_submit'),
        '#value' => t('Cancel'),
    );
}
function cancel_submit() {
    $response = new Symfony\Component\HttpFoundation\RedirectResponse(Url::fromUri('internal:/admin/mymodule/list', array('absolute' => true))->toString());
    $response->send();
}

I can't get this to work because it's still trying to validate the form.

In my form code, my validation code will only execute if if ($form_state->getValue('op') == 'Save') is true, and this evaluates to false for the Cancel button. However, while this is stopping my custom validation code from running, it isn't stopping built-in validation for fields that I defined as required in the Drupal interface. The cancel_submit function doesn't seem to be doing anything, and clicking the Cancel button just loads the form again with a validation error on a required field.

I also tried adding '#limit_validation_errors' => array(), to $form['actions']['cancel'] as recommended here, but this just refreshed the form without showing validation errors instead of redirecting where I want it to go, so I have no idea what this code is actually doing or if this is even applicable for Drupal 8.

I am not sure where to go from here.

To send a redirect response from a form use setRedirect() or setRedirectUrl():

  function cancel_submit(array &$form, FormStateInterface $form_state) {
    $form_state->setRedirectUrl($url);
  }

And add '#limit_validation_errors' => array() to the cancel button as already mentioned in the question to prevent validation errors.


Translation of a element['#object'] rendered field I have some fields in which I rendered additional fields from a nested term via element['#object']:

e.g. {{ element['#object'].field_country.entity.name.value }}

Unfortunately, this fields do not translate inside the node view although the node and the nested term itself is translated.

How can I make them display with their translation?

Use getTranslation(), see How to load translated entity values in Twig for SEO purpose?.

In your case you can try something like this:

{% if element['#object'].field_country.entity.hastranslation(element['#object'].langcode.value) %}
  {{ element['#object'].field_country.entity.translation(element['#object'].langcode.value).name.value }}
{% else %}
  {{ element['#object'].field_country.entity.name.value }}
{% endif %}


Is it possible to extend an existing contributed module? There's a new Drupal module that I'm interested in integrating in our websites, the Media Entity File Replace module. I've already installed it via composer and created an update hook to enable it across our different profiles, but the problem is exporting its yml configuration file.
Step 3 of the module's Usage Instructions says you have to enable it in the Form Display settings of the media type you wish to use it on. In our case, we just want it on Documents media type.
I looked for the yml configuration under Entity Form Display and found that it updates this particular file:
core.entity_form_display.media.document.default.yml
I run a search in my local Drupal branch and found that that file only exists in the Acquia Lightning Media contributed module (docroot/modules/contrib/lightning_media/modules/lighnting_media_document/config/install/)
How would I safely utilize the Media Entity File Replace Module without breaking a contributed module?

If you're using core's configuration sync to manage your site's config, you should be able to update this through the UI, then export your site's configuration to the sync directory, e.g. drush cex sync. This will create a new file in the config sync directory for the updated config which can be safely committed along with your other changes. While deploying, you'll need to import the synced configuration, e.g. drush cim sync to import the UI change on your second environment.
Configuration files in a module's config/install directory are only read from that location when the module is installed. That configuration file shouldn't change at all here and there's no reason for it to.


How can I automatically upload images on file selection rather than pressing the upload button? I have a custom content type to allow users to upload images.  I'm trying to keep the interface as simple as possible.

The content type contains a single image field.  This works, but some users don't understand that the image has been uploaded because they don't see it after selecting (to preview the upload, the upload button must be pressed).  Is there a way to skip/automatically press the upload button so that an image is shown immediately after a file is selected?

In other words, immediately after selecting a file, instead of the following picture (where the path is shown but hard to read in Firefox):

I'd like the preview display to be shown like this:

You'd be better off doing this at the module level, rather than the theme level, as the JS will not take effect for admin pages otherwise (unless of course you're using the same theme for both).

Here's a small module to provide this functionality system-wide:

File: auto_upload.info

name = Auto Upload
description = Removes the need for users to press the 'Upload' button for AJAX file uploads.
core = 7.x
dependencies[] = file

File: auto_upload.js:

(function ($) {
  Drupal.behaviors.autoUpload = {
    attach: function (context, settings) {
      $('form', context).delegate('input.form-file', 'change', function() {
        $(this).next('input[type="submit"]').mousedown();
      });
    }
  };
})(jQuery);

File: auto_upload.module

function auto_upload_init() {
  drupal_add_js(drupal_get_path('module', 'auto_upload') . '/auto_upload.js');
}

Once you've installed the module all file inputs that are AJAX-ified (i.e. those that have an 'Update' button) will be affected...you won't need to press the 'Upload' button any more after selecting the file.

By using the delegate() method this will also work perfectly for file fields that allow multiple uploads, and also for fields that are loaded into the page as the result of an AJAX request.

I've tested that in Chrome, Safari and Firefox and it works a treat :)

Footnote: In the (probably very unlikely) event that your site is using jQuery 1.7, you should use the on() method, which has superseeded delegate().

UPDATE I've created a sandbox project for this module.


Call to undefined function field_attach_load() on a newly migrated site I am moving a site over to a different server to test.
I am getting the following error:

Call to undefined function field_attach_load() in my-path-to-root/my-site/includes/entity.inc on line 320

If I try accessing http://www.example.com/randomstuff, I get this error:

Fatal error: Call to undefined function user_access() in /home/borsodas3/digipowers.devserver2012.com/modules/overlay/overlay.module on line 130
Fatal error: Call to undefined function node_access_needs_rebuild() in /home/borsodas3/digipowers.devserver2012.com/sites/all/modules/taxonomy_access/taxonomy>_access.module on line 598

phpinfo() returns following information for the two sites:

Source site
Destination site

The Drupal status report from the site I am migrating FROM looks like this:

Info
Drupal  7.8
OK Access to update.php Protected
Error CTools CSS Cache  Unable to create
The CTools CSS cache directory, ctools/css could not be created due to a misconfigured files directory. Please ensure that the files directory is correctly configured and that the webserver has permission to create directories.
OK  Configuration file  Protected
OK Credit card encryption   Credit card data is encrypted during checkout for maximum security.
OK Cron maintenance tasks   Last run 26 min ago
You can run cron manually.
To run cron from outside the site, go to mysite.com
OK Database system  MySQL, MariaDB, or equivalent
OK Database system version  5.1.57-log
OK Database updates Up to date
OK Date API System date settings
The timezone has been set to America/New_York. The first day of the week has been set to Monday. The medium date format has been set to to F j, Y - g:ia.
Error Drupal core update status Not secure! (version 7.12 available)
There is a security update available for your version of Drupal. To ensure the security of your server, you should update immediately! See the available updates page for more information and to install your missing updates.
OK File system  Writable (public download method)
OK Fitvids library  Installed
Fitvids Javascript Library. Download it from here, copy it to the module directory, and rename it to jquery.fitvids.js.
OK GD library PNG support   bundled (2.0.34 compatible)
OK GD library rotate and desaturate effects bundled (2.0.34 compatible)
OK Images   Product image support has been automatically configured by Ubercart.
Error Module and theme update status    Not secure!
There are security updates available for one or more of your modules or themes. To ensure the security of your server, you should update immediately! See the available updates page for more information and to install your missing updates.
OK Node Access Permissions  1832 permissions in use
If the site is experiencing problems with permissions to content, you may have to rebuild the permissions cache. Rebuilding will remove all privileges to content and replace them with permissions based on the current modules and settings. Rebuilding may take some time if there is a lot of content or complex permission settings. After rebuilding has completed, content will automatically use the new permissions. Rebuild permissions
OK PHP  5.3.2 (more information)
OK PHP extensions   Enabled
OK PHP memory limit 300M
OK PHP register globals Disabled
Warning Unicode library Standard PHP
Operations on Unicode strings are emulated on a best-effort basis. Install the PHP mbstring extension for improved Unicode support.
OK Update notifications Enabled
Info  Upload progress   Not enabled
Your server is capable of displaying file upload progress through APC, but it is not enabled. Add apc.rfc1867 = 1 to your php.ini configuration. Alternatively, it is recommended to use PECL uploadprogress, which supports more than one simultaneous upload.
OK Web server   Apache/2.2.3 (CentOS)
OK cURL Enabled

I had this same problem today and I fixed it by simply running the update script:

The update script is located in the root folder of your Drupal 7 install.
eg.

  www.mynewlymigratedtoserver.com/update.php

One other thing you should probably know, you have to be logged in to run the update script, you can login right? No, you can't! That's ok, there's a work around.

In your settings.php (usually /sites/default/settings.php) there is a line (231 for me) that says this:

  $update_free_access = FALSE;

This variable determines if the update script can be used by anyone, not just logged in people. Set it to TRUE and you'll be able to run the update script. You'll want to set it back to false when you're done.

If that didn't work try this


"Rate Module" How to put the number inside the button? http://drupal.org/project/rate

As you can see, the "yes/no" widget on the bottom of the screenshot is:

[button] [number]

The number is not part of the button.  How to make it like this instead:

[button number]

edit: a perfect example, the thumbs-up/thumbs-down rating widget on Yahoo Answers: http://answers.yahoo.com/question/index;_ylt=Ao37OQz9iO3ZJvacOl9pH8_j1KIX;_ylv=3?qid=20121104010935AAs5NQk

The number is in the button.  Clicking anywhere on that button registers a vote.

This is done by using some CSS.

look at the HTML structure there. 'LI' tag is used there. Just use the anchor style to LI tag.

background: #EEE;
border: 1px solid #CCC;
margin-right: 3px;

Use this style to li and remove anchor border. Also change the hover style of anchor tag.

Use firebug to find the structure.


Dompdf returns PDF on Controller function but not on Submit Form function I'm using Drupal's Form api to create a form which returns some values inside a PDF document based on some selected inputs. I'm importing the form like so:

public function content(){
    $form = \Drupal::formBuilder()->getForm('Drupal\custom_module_name\Form\ContributeForm');
    ...
    ... and so on

In my ContributeForm::submitForm I have this code:

public function submitForm(array &$form, FormStateInterface $form_state)
{
    $dompdf = new Dompdf();
    $dompdf->loadHtml('
hello world
');
    $dompdf->setPaper('A4');
    $dompdf->render();
    $dompdf->stream("example.pdf", array("Attachment"=>0));
    if ($dompdf){
        drupal_set_message("DOMPDF");
    }
    foreach($form_state->getValues() as $key => $value){
        drupal_set_message($key . ': ' . $value);
    }

and I don't get a pdf doc on the reloading of the page, though I do get the contents selected in the form returned to me in the drupal_set_message call.

Now to sanity check, I created a dummy module with only a controller (no form import) and this one DOES return the PDF with the content inside ::loadHtml:

public function content(){

    $domp = new Dompdf();
    $domp->loadHtml('
Hi
');
    $domp->setPaper('A4');
    $domp->render();
    $domp->stream('example.pdf');

    return array(
        //'#type' => 'markup',
        '#markup' => $this->t('Hello World yall'),
    );

}

Am I missing something on the form return? Am I adding an unnecessary layer of complications by importing the form into the controller, and should I just have the form load to it's own url?

By default after form submit drupal makes a redirect, if there is no redirect defined intentionally allways will go to current url. To prevent this, you need call to disableRedirect() method from FormState at the final of submitForm().

Example:

public function submitForm(array &$form, FormStateInterface $form_state)
{
    $dompdf = new Dompdf();
    $dompdf->loadHtml('
hello world
');
    $dompdf->setPaper('A4');
    $dompdf->render();
    $dompdf->stream("example.pdf", array("Attachment"=>0));
    if ($dompdf){
        drupal_set_message("DOMPDF");
    }
    foreach($form_state->getValues() as $key => $value){
        drupal_set_message($key . ': ' . $value);
    }
    // Prevent form redirection to print PDF.
    $form_state->disableRedirect();
}

Source: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21FormState.php/function/FormState%3A%3AdisableRedirect/8.2.x

Other option, more dirty, is call to exit() method from PHP (http://php.net/manual/es/function.exit.php) also at the final of the function.


Why cannot I print $form in my template file? I have a "video" content type. I want to customize the template file for edit form,
page--node--add--video.tpl.php, but when I render (or print) $form, it returns NULL.

What is the problem?

There's no $form variable available in page.tpl.php (see the docs for a full list of available vars).

If you're trying to output the page content it's done like so:

<?php echo render($page['content']); ?>


Can't we sort a "Node module element"? I'm creating a new content type named "Portfolio".

Image 1: I put a name to the "Title field label": Project Name

Image 2: That thing works as a 'Node module element' in Fields

Image 3: I can't get the Field to sort it below the Project Image

I even can't get this 'Node module element' from Views (using Views module). The sorting problem is specific to "Teasers" in the portfolio page:

I just want the Project Title to sort a bit so that I can place the title just after the Project Image. I'm familiar with WordPress, but a newbie in Drupal.

There are three ways to go about.

1) Use views. In views the Field to add is Content : Title. (Even if you change the name of the title field it is still title. It is just changing the label on the form.)

2) You can install Display Suite Module. Once you install this module you would get additional fields once you select a layout in the layouts section.

  Display Suite allows you to take full control over how your content is
  displayed using a drag and drop interface. Arrange your nodes, views,
  comments, user data etc. the way you want without having to work your
  way through dozens of template files.

3) The third method is to work with the node.tpl.php you have a node object. Since you are using teaser the title would be available in a field. All the other fields can be accessed from the node object.


How to use custom modal with ctools and triggered by a button form I'm using ctools to render my node form.
And my quesiton is how to insert the custom style for the popup window.
I know how to use the custom style in the text button. but I don't know how to use it in the button form

the code for my button form

function hs_ajax_button_form($cmp_id=NULL)
{
    $form = array();
    $slogan_url='hs_ajax/nojs/slogan/'.$cmp_id;
    $form['url'] = array(
    '#type' => 'hidden',
    // The name of the class is the #id of $form['ajax_button'] with "-url"
    // suffix.
    '#attributes' => array('class' => array('hs-ajax-button-url')),
    '#value' => url($slogan_url),
    );

    $form['ajax_button'] = array(
    '#type' => 'button',
    '#value' => t('New Post'),
    '#attributes' => array('class' => array('ctools-use-modal')),
    '#id' => 'hs-ajax-button',
    );

  return $form;
}

and my trigger code is below

 $button_form=hs_ajax_button_form($campaign_id);

                    $form['PlayerAttendInformation'][$key]['ctools']=array(
                    '#type'=>'markup',
                    '#markup'=>drupal_render($button_form),
                    );

my style is as below

    $sample_style = array(
        'slogan-style' => array(
          'modalSize' => array(
            'type' => 'fixed',
            'width' => 800,
            'height' =>700,
            'addWidth' => 20,
            'addHeight' => 15,
          ),
          'modalOptions' => array(
            'opacity' => .5,
            'background-color' => '#000',
          ),
          'animation' => 'fadeIn',
          'modalTheme' => 'CToolsSampleModal',
          'throbber' => theme('image', array('path' => ctools_image_path('ajax-loader.gif', 'hs_ajax'), 'alt' => t('Loading...'), 'title' => t('Loading'))),
        ),
        );

how can i do that?

Try this:

  $form['ajax_button'] = array(
    '#type' => 'button',
    '#value' => t('New Post'),
    '#attributes' => array('class' => array('ctools-use-modal','ctools-modal-slogan-style')),
    '#id' => 'hs-ajax-button',
    );

Vincent


hook_theme default arguments not recognised in template When using hook_theme I create an array of variables with default values:

/**
 * Implementation of hook_theme
 */
function my_module_theme() {

  return array(

    'my_theme' => array(
      'arguments' => array(
        'var1' => 'default value',
      ),
      'template' => 'my-theme',
    ),

  );
}

And the template file my-theme.tpl.php:

<?php print $var1; ?>

But inside the corresponding template the $var1 variable is only recognised if I explicitly send it with the theme() implementation:

print theme('my_theme', array('var1' => 'New var'); // No errors

print theme('my_theme'); // Notice: Undefined variable: var1 in include()

My understanding of the default arguments are just that - they should be the default if they are not explicitly defined. What am I missing?

You have to do like

/**
 * Implementation of hook_theme
 */
function my_module_theme() {

return array(

'my_theme' => array(
  'variables' => array(
    'var1' => 'default value',
  ),
  'template' => 'my-theme',
),

);
}

Instead of arguments use variables.

Hope this will help.


Let user pick background Image/Color on node form I would like to allow my users to choose a background image or color for a node. I created a content type with two fields: 'background image' of type image, and 'background color' of type color field.

I can retrieve the values of the fields on my module but how can I pass them to my stylesheet? Should I use the style attribute of my HTML elements?

The background color can be any color so I can't precreate css classes, or files.

Any idea on how to do this? Thank you!

I suggest you do it in your  node.tpl.php. You can add the style attribute directly to the attributes array in a node preprocess.

in your template.php , load(add css file ) or insert in-line css style

function THEMENAME_preprocess_node(&$variables) {
  $type = $variables['type'];
   // dpm($$variables['node']);
  // as example
 if($color=$variables['node']->field_color['und'][0]['value']){
 $css = "p {background-color: $color }";
 drupal_add_css($css, 'inline');
   }
 }

you can do something like this .I hope this solution get you some good clue .


feeds importer importing from several sources Is it possible to run one feed importer on several sources?

Currently my code is as follow:

My importer module file is

function myModule_import_feeds_plugins() {
  $info = array();
  $info['xml_parser'] = array(
    'name' => 'XML feed parser',
    'description' => 'Imports XML feed.',
    'help' => '',
    'handler' => array(
      'parent' => 'FeedsParser',
      'class' => 'myXmlParser',
      'file' => 'my_xml_parser.inc',
      'path' => drupal_get_path('module', 'myModule_import') . '/plugins/feeds',
    ),
  );

My parser is:

class myXmlParser extends FeedsParser {

  /**
   * Implements FeedsParser::parse().
   */
  public function parse(FeedsSource $source, FeedsFetcherResult $fetcher_result) {
    $feed = new SimpleXMLElement($fetcher_result->getRaw());
    $source_feed = $source->config['FeedsHTTPFetcher'];
    $user_tags = isset($source_feed['user_tags'][0]) ? explode(',', $source_feed['user_tags']) : array('tag1', 'tag2');

    $result = new FeedsParserResult();
    $result->title = 'feed importer';
    $result->items = array();
    #$fetcher_result->
    foreach ($feed->channel->item as $item) {
      // Skip if title doesn't
      if ((string) $item->title) {
        $result->items[] = array(
          'title' => (string) $item->title,
          'callout' => '<p>'.(string) $item->description.'</p>', // wrap light_html in P tags
          'pubdate' => (string) $item->pubDate, // _parser_common_syndication_parse_date()
          'url' => (string) $item->link,
          'image_url' => (string) $item->thumb, // http://placekitten.com/g/200/300
          'image_alt' => (string) $item->alt,
          'published' => 1,
          'tags' => $user_tags,
        );
      }
    }

    return $result;
  }

feed screen looks like this

I would like to add an additional field for an optional URL. This way the user can include several sources and import from different places at the same time.

I could not find a way to do so. Ideas?

Yes, there is. The supported way of importing multiple sources for one importer is to attach the importer to a content type (which can be configured under the "Basic settings"). Attaching an importer to a content type means that a node must be created to import content. Since you can create multiple nodes, you can import multiple sources with one importer configuration.

Be sure though that if you are importing nodes (using the Node processor) that the nodes you create are of a different type than the node type that you attach an importer to. It is wise to create a new content type that is specifically only used for your importer.

See also my answer at https://www.drupal.org/node/2854548#comment-11948926 for more information about why you should not attach an importer to the same content type as the one you select on the processor settings.


How do I make node_gallery image thumbnails retain original proportions? When I upload an image to a Drupal 7 node_gallery gallery, a thumbnail is automatically generated. This is good.

However, the thumbnail is also cropped to a square size. This is bad. (But note that the full-sized image is not cropped.)

I want the thumbnail to retain the original image proportions (often 2:3 or 3:4), the same as the full-sized image (just smaller), rather than being cropped to a 1:1 format.

How can I do that? Google was distinctly unhelpful in this case, showing me results only for old versions of Drupal, and even then those solutions were mostly for other problems.

Never used this module, but try checking /admin/config/media/image-styles perhaps the module has an image style. If so, all you have to do is edit it and change it to your liking.

Side Note: You can also get there by clicking configuration, then under media click on Image Styles.

As you wrote in a comment:

  Editing the node_gallery_thumbnail style to replace the "Scale and crop" effect with a "Scale" with the same numbers for width and height did the trick.


Why disable non-core modules when doing a core update? I have seem multiple update tutorials tell you to disable all non core modules before doing an update. What is the reason for this? I'm not real familiar with the update area of core but can't see any real good reason. Is there something major I am risking if I don't do this?

I can understand the reasoning if we are doing an update between major versions (6 -> 7). But when doing a minor update (7.10 -> 7.12) is where I have my question.

Contributed modules are not always robustly built and can fall victim to changes made in core. This is particularly an issue if the contributed module has not made proper use of Drupal's API or relies on a database structure in core that may change with the upgrade (even if it is just a minor update). It is therefore safest to disable all the contributed modules before updating in case one of the modules causes the site to fail on completion of the upgrade process. Admittedly this is rare, but it does happen. It happened to us once, but thankfully just on a dev version of a site.


How long does it take for Drupal to unblock user after 5 failed attempts? I've tried to log in unsuccessfully to Drupal and I get the following error:

There have been more than 5 failed login attempts for this account. It is temporarily blocked.

Does anyone know how long the waiting time is for localhost?

To answer your question:

  The amount of failed logins is recorded in the table 'flood'. You can
  either wait before trying to login again (6 hours) or clean the
  flood table with the procedure below.

Options for not having to wait:

  Execute the following query on the Drupal database:

  DELETE FROM 'flood'; If command above doesn't work try this:

  TRUNCATE flood RESTART IDENTITY; To execute this query it will be
  necessary to login to the database. This is typically done through the
  command line or through a GUI interface such as phpMyAdmin. If Drush
  is installed on your server, the drush sql-cli command provides quick
  access to an SQL command-line interface.

  From the command line, with Drush installed:

  drush php-eval 'db_query("DELETE FROM `flood`");' NOTE: The query
  above will delete ALL entries in the flood table. If you want to
  remove only a specific user's entries from the flood table, the
  following is more specific.

  DELETE FROM flood WHERE event = 'failed_login_attempt_user' AND
  identifier LIKE '1234-%'; (where 1234 is the UID of the blocked user)

Source: Login blocked after 5 failed login attempts

Want to change the settings for this? You can by installing Flood control


Why do I need to use .live() in Drupal Behaviors? I am trying to be a good boy and use Drupal Behaviors to manage my JavaScript. My understanding is that one of the advantages of using Behaviors is that it frees you from having to use .live() to bind event handlers to dynamically created elements. However, I find that I have to use .live() all the time. What am I doing wrong?

Here is a simple example of what I'm talking about:

Drupal.behaviors.MySearch = {

  attach: function (context, settings) {

    var searchBox = $('#my-search-box');
    searchBox.append("<input type='text'></input>");
    searchBox.append("<button>Search</button>");

    $('#my-search-box button').click(function(){
      console.log("This does not work.");
    });

    $('#my-search-box button').live('click', function(){
      console.log("This does work.");
    });

};

My understanding is that one of the advantages of using Behaviors is that it frees you from having to use .live() to bind event handlers to dynamically created elements.

Yes and no. It certainly can be used for that, but it will only work if Drupal has invoked the previous AJAX call. If you've just done a $.ajax(...), Drupal won't know about it, and attachBehaviors() won't be invoked.

I would guess that your attach() method is indeed only being invoked once, as it would explain perfectly why the click handler is assigned once (when the page is first loaded), but not again. The live() will always work no matter how many times your attach() method is called.

If that is the problem, to fix simply add this to your AJAX success callback:

Drupal.attachBehaviors();


Student TV channel - taxonomising YouTube videos This question has been created to break up a previous question; see there for more detail.

As you can guess from the title, I'm the new webmaster for a student TV channel and I need to update the site.

The site needs to pull in YouTube videos from a channel, embed the video player and display a brief description of the video, along with information about the cast & crew involved in the production. Similar videos (such as those in a series) need to be linked together in a "playlist" style, while other videos should be browsable through a gallery based on genre.

Does anyone know what the most effective way to taxonomise these videos would be? I'm thinking of fields genre and series at the moment, but I don't know how I could list cast & crew members. (Videos need to be organised so you can quickly find all of the videos with a cast/crew member involved with)

I suggest using series and genre as the main taxonomies as you've said and then using Tags to generate a taxonomy for cast and crew.

You can use the Taxonomy Manager module to bulk add and edit taxonomies, including tags.


How can I programmatically get a checkbox value? I need to check if "Close this ticket after replying" checkbox is checked or not. The value $ab is not getting displayed. This is a comment type created from Structure > Comment Type.
function helper_ticket_comment_submit(&$form, FormStateInterface $form_state)
{
          $ab = $form_state ->getValue('field_close_this_ticket');
           \Drupal::logger('CheckBoxValue')->notice($ab);

 }

Error:

Install the Devel module and then use its dpm() function to print a variable to the message area of your page. So inside your submit handler put dpm($form_state->getValue('field_close_this_ticket')); and you'll see what the error message already is telling you: It's an array. While the logger expects a string. What you are looking for is inside $form_state->getValue('field_close_this_ticket')['value'], note the ['value'] at the end.
function helper_ticket_comment_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {

  if ($form_state->hasValue('field_close_this_ticket') && $form_state->getValue('field_close_this_ticket')['value'] == TRUE) {

    \Drupal::service('messenger')->addMessage(t('Ticket closed'));
  }
}


Content not showing up by default with exposed filters I have a view with 2 taxonomy term fields. I have these fields presented as expose filters for site users to select from dropdown, which works fine. However, when I first land onto the view page, none of my content is showing up. All I see is a blank view.
However, if I click apply, with all the fields unselected (e.g. - Any -), then all my content shows up. How do I make the content show up by default without having to click on Apply?

Upon landing on the page for the first time:

After clicking Search:

In exposed filter section try to deselect all values in Select terms from vocabulary Event type field


Views simply won't output HTML at all for me in any content types, what to do? I have Installed Drupal 7.26 (Default Installation), and on a Fresh Installation, I have Views Module (CTools All Sub Modules Installed) and PathAuto Module installed ONLY.  OK, So I create a Content Type and delete the Body Field that is created by default, and create another Field called Section and have it set to LONG TEXT, than make it filterable in the settings so that the user can select the text format, and have it set to an UNLIMITED amount of areas, with required UNCHECKED.

I than create 1 node using this content type with FULL HTML selected as the text format for each section and save it.

I now go to the Views Module and attempt to use an Unordered List, of Fields and select Content: Section as the field, The formatter is set to Default, I set a filter on it for Content Type and select Is One of That content types name.  I see nothing in the preview at the bottom and so I go ahead and save it anyways as it should show something.  I have the page path set to node so that it shows up on the front page.  However, there is nothing being returned for the output of this view on the Front Page.

No matter what theme I choose, I can not get HTML to output in this view whatsoever.

Is there some sort of settings I have not performed somewhere?  I go to Reports -> Status and everything checks out fine.  All Green sections there.  I go to run Cron, again, no problems whatsoever so it seems.  How to debug this?  Or is this an actual confirmed bug in Views?  Or Drupal?  Or something else?

If I change the type from Fields to Content, it still shows no body content, but now only shows the Title of the Content and links to the Page where it is located at, but on that page, it shows nothing but the title.  How can this be fixed?  OMG, this is a nightmare.  I've been trying to hunt down the problem for days with no luck at all!

"node" is registered menu path by node module
You should not set a page path "node" which already exists.
Create a block view using views instead of page view
Enable the block on home page


Reject Form Submissions with URL in them I have a client who is using Drupal and has an email contact form.  The problem is they are getting spam sent through the form daily.

I have tried the Re-captcha plugin, captcha plugin, Anti-spam (Askimat), and Honeypot plugins.

The offenders are using programs like XRumer which is capable of solving captcha's and none of these plugins have been able to stop the bots.

So I am asking others if they have any advice on how to stop these contact form spam submissions?

Since this particular form shouldn't have a legitimate reason for a URL in the body section, possibly I could detect URL's and then return an error if they are present when a form is submitted?

It is possible to create contact forms using either the Webform module, or the Entityforms module.

The beauty of the latter is the ability to attach fields, and to validate those fields with the Field Validation module, which offers a wide range of validation options.

There is a Webform Validation module for use with Webforms, but I think you will find Entityforms with Field validation to be a little more flexible and, perhaps, easier to use.

Either one should let you scan text for say "<a href=" or any other undesireable word or phrase (blacklist matching) or constructs using regular expressions, if you are so inclined.


attachment views and pager I have created a overriden taxonomy term page using views, page displays and attachment displays. A term landing page looks kind of like this:

3 articles showing image as a list (page display)
3 articles without showing image as a list (first attachment display)
6 articles in 2 column table (second attachment display)

I would like to somehow enable paging on this thing. Ideally the pager would sit on the bottom of the last attachment. When a user goes to page 2 (assuming a page size of 12), the first (page display) view would show articles 13 to 16, the first attachment from 17 to 19 and so on.

Is this possible?

If you're using Views 3:

While I don't know how to exactly do what you want purely with Views (or even if it's possible), I can suggest you a module called Display Suite which can work with Views. You can define different display modes for nodes first, and then go to Views and choose "Node Display" type of output, and define in the settings which article should be displayed with which display, for example First 3 nodes in the list should use "Teaser with Image" display, next 3 would use "Teaser without Image" display, and then the next 6 would use a normal "Teaser" display. Then you can use CSS to define the columns for the last 6. Doing it this way you eliminate having the need to use Attachments, so all your results come from 1 display. Pagers then should work normally. I cannot guarantee you this will work 100% as I haven't used this module by myself, but I've seen a colleague implement something like this before, and he also had problems with using Pagers. I'm not sure if this functionality is compatible with Views 2 as it's been a long time since I used Views 2. Good luck.


Suppress Incorrect error message My website is using Drupal 7, secure login, and r4032login. I get this message when I log into a page that was redirected to the login page when access was denied:

  You are accessing  using an unencrypted connection. For your security,  only supports account logins using a secure protocol such as HTTPS. You can switch to HTTPS by trying to view this page again after changing the URL in your browser's location bar to begin with "https" instead of "http". Please contact  for help if this error continues.

This is untrue, as every time this message appears the sites url is https://www.mysite.com
What can I do about his message? What is the underlying cause? How can I suppress this if it can't be solved?

Update: This is not being caused by r4032login or secure login. I disabled and unistalled these module, and after logging in, the message is still displayed.

Turns out this error message was being created when clicking on a link that had http selected as its protocol.


Is it possible to attach discussion board to a node? I have a content type called "Movies". I would like to create discussion threads  under it similar to discussion threads in imdb.com under a movie. I have tried the advanced forum module and also brain forum module. They don't seem to do that I have in my mind.

Is there a module which does this job? I think I will have to use advanced forum module and use a content type for forum discussion and then use entity reference and entity reference prepopulate to link it to the other content type. Is there a better and cleaner way to do this?

Use the core comment module.

(If you want to order the newest comments at the top then see Comment goodness)


page not found after restoring from the backup except home page (Tried all solutions, which I got through googling)? I restored my site from the backup taken from another computer. Another drupal site is working fine in my machine, but this site which I restored from a backup is not working fine.

I am able to see the home page, front page but not any other pages of this restored site. when I click on links displaying 404 error (page not found).

When it is working for some other site, it has to work for other also. But I am missing some site specific configurations.

could any body please help me in this regard

Looks like you have lost your .htaccess in the process. Download newest Drupal core from Drupal.org, extract it and put .htaccess in the root directoy of your Drupal. If this still does not work, and your .htaccess is ignored, go to official Clean URLs documentation, and find a section Server configuration for Clean URLs on a dedicated server, with httpd.conf - this should show you how to configure it properly.


Add Profile 2 -> Field Colleciton -> Taxonomoy into Facet (Search API) I'm trying to display a Facet block , which uses Term reference (Taxonomy) of Field Collection of Profile 2. Since I am new to Search (API), I have tried all sort of things but nothing worked.

For example:

Use Facet display of View: Rendered entity, Field..
Use Facet Block from Search API
Config options in Search /Search API..

In
Home » Administration » Configuration » Search and metadata » Search API » View index

I added Facets the followings:

Vocabulary: Facet blocks look good in the picture below
Profile2->Field Collection: look good in the picture below
Profile2->Field Collection->Vocabulary(Taxonomy): bad,It always shows empty

My Question is:

How can I make this happen? or Is it possible to do it?

I found out the solution from Search API Drupal Recruiter  here

In short, I have to click "+Add index" to make a new index based Profile

For example, Please take a look at the picture below to understand how to solve this issue.


Putting any fields of referenced entity in lightbox frame I want output a field as a link to an overlay that has fields of a referenced entity in it.
I can output the actual link just fine as long as it doesn’t have to be an overlay.
Content type A is called ‘performance’, content type B is ‘performer’ (to which is being referenced).

So, for now, in my view there are only two fields: ‘Performer name’(of content type B also the title) and ‘title’ (of content type A). ‘Performer’ is arranged above ‘title’ and display set to none. ‘Title’ has ‘ouput field as link’ checked and has the token in the URL that is the title of ‘Performer’.

So this makes the link that is the title in the view go to the node of the performer that is referenced in the ‘Performance’ node.

I know that in the ‘rewrite results’ fieldset, I can fill in ‘lightbox2’ in the ‘rel’ attribute of my link. When I do this though, the lightbox shows, but is empty. No image, no values of any field, no nothing.

This doens't necessarily have to be done using lightbox. It ended up being a lot easier using a jQuery plugin like Simple Modal

I made extra fields in views and gave them a class the jQuery could latch on to using

$('hideMe').hide;

and using jQuery's click(); method to go and say (this).modal

A different question here at Drupal Answers went into the same issue but it was more about how to write the jQuery code so definitely more of a jQuery question. Anyway the question with the exact code can be found here.


Implementing IP recognition and price conversion (2 parts) The commerce (kickstart) site has default prices in USD. Site should convert the price to local currency for international visitors, based off IP or other means.

Example:

Widget Price - $2 (USD).

Australians see: A$2.15

Canadians see: C$2.18

Japanese see: ¥204.70

So the functions needed are

Detect country from IP
Lookup visitor's currency
Lookup conversion rate from USD
Convert + format price
Display wherever price field is called.

There doesn't seem to be a single module to do this (I wish there is!) and bits and pieces of advice here and there which involve rules etc, which I'm not familiar with.

I hope I can find a guru here who can show the way. Thanks!

I don't think there is any module provides this functionality.. The best way is to use some third party services to get data and display it..

I'd do such things to acheive this:

get user ip by ip_address()`
get user info by this service: http://www.geoplugin.net.

here is an example:

$countryInfo = drupal_http_request('http://www.geoplugin.net/json.gp?ip=' . $user_ip);
$countryInfoData = json_decode($countryInfo->data);
$userCurrencyCode = $countryInfoData->geoplugin_currencyCode;

and use google converter to get result:

some sample code:

  $amount = urlencode($amount);
  $from_Currency = urlencode($from_Currency);
  $to_Currency = urlencode($userCurrencyCode);
  $get = file_get_contents('https://www.google.com/finance/converter?a=' . $amount . '&from=' . $from_Currency . '&to=' . $to_Currency);
  $get = explode("",$get);
  $get = explode("",$get[1]);
  $converted_amount = preg_replace("/[^0-9\.]/", null, $get[0]);

this piece of code's gotten from this post :)

and, so, it's up to you to display the results...

I don't think this is a real solution to your problem and also I can't guarantee this will work:) .. but you can play around it to find better solution..


How to send a webform email to all users of a specific role? Is it possible send webform data in email to all users of a specific role?

In the webform email settings there is no such option.

I also tried with Rules, but in rules the webform tokens are rendering the webform submitted data.

Here is my rule attached.

{ "rules_send_email_to_ce_user_on_webform_submit" : {
    "LABEL" : "Send email to CE user on webform submit",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : "[form-id:value]",
          "selected_webform" : { "value" : { "webform-client-form-121" : "webform-client-form-121" } }
        }
      }
    ],
    "DO" : [
      { "webform_submissions_load" : {
          "USING" : { "nid" : "121", "sid" : [ "data:sid" ] },
          "PROVIDE" : { "submissions" : { "submissions" : "Fetched submissions" } }
        }
      },
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "11" : "11" } },
          "subject" : "Form submission from: [node:title]",
          "message" : "DATA\r\n[data:data]\r\n\r\nRAW\r\n[data:data-raw]\r\n\r\nField value\r\n[data:title-value]"
        }
      }
    ]
  }
}

Any other method?

From the exported rule in your question, it seems you already have the Webform Rules module enabled (a prereq for what follows ...).

You may want to give it a try to process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

Load the VBO list that you want to be processed.
Add a loop to perform a Rules Action, for each row contained in your Views results.

Some more details about the VBO-view you'd have to create for this:

Create a list users, using the Views module.
It should include an appropriate filter for the role to be processed.
It should have exactly 1 result (row) for each user to be eMailed.
One of the columns should be the eMail Id (I don't see other columns needed for this to work).

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".


Menu block doesn't appears where I expect it I have this kind of menu:
"Level 1" has menu item "Level 2", which links to the page with "cat1" url. Then, I have node which have aliases "cat1/[nid]", hence, in my opinion, menu block (provided by "menu block" module) should appear. But it doesn't. Why?

If you haven't worked with menu block module and not familliar with it, then how can I force to show "Level 1 -> Level 2" menu part if a node with alias "cat1/[nid]" is loaded?

Solved that! Inspecting the code of Menu Block cleared it out for me that this module doesn't work with URLs. What a pity!

But:

There is a completely awesome bunch of modules: Context withContext:Menu Block which make it possible.
Context menu block modules make Menu Block module being aware of context. Also this page may be useful.

But still, if you have better solutions, please write it here.


.htaccess https rewrite for single domain on multisite installation I have a multisite installation with 2 sites running off separate domains. One of these sites needs to go through https:// while the the other can stick to http://. I also want all traffic to be rewritten to include the www. prefix.

So:

example.com rewritten to https://www.example.com

example.co.uk rewritten to http://www.example.co.uk

I'm trying to set my .htaccess file to handle this, and have tried with the  syntax discussed here.

RewriteEngine on
<If "%{HTTP_HOST} == 'example.com'">
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</If>
<If "%{HTTP_HOST} == 'example.co.uk'">
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !http
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</If>

Needless to say, it's not working. Any input would be much appreciated!

First I would try using the [drupal]/sites/sites.php file to do something like this:

$sites['example.co.uk'] = 'example.com';
$sites['example.com'] = 'example.com'; // for demonstration only

Then check out the htaccess module to force HTTPS. These are the  options:


What permission is required to access node reference data? I created a CCK field (claim_category) in a CCK type (claim), added a few claim_category nodes.

When I try to create a new claim node (/node/add/claim), admin can see the claim_category drop-down list fine. However, an authenticated user sees an empty drop-down list with no option in it.

What permission is required for an authenticated user to to access the drop-down list data (claim_category nodes)?

Note: CCK Content Permission module is not enabled.

After I add a dummy CCK field in claim_category, the list show up properly.


Leaflet library not avaliable even though it's in sites/all/libraries I've seen people talking about hook_library() etc., but I'm not creating a custom module, I'm trying to use Leaflet. In the browser I get the error message:

L is not defined

From leaflet.drupal.js in my sites/all/modules folder. I've got the Leaflet and Libraries modules installed and enabled, and the Leaflet files are extracted under sites/all/libraries/leaflet.

Anyone have any idea what I'm doing wrong?

Looks to me like the library hasn't been installed correctly, the path should be sites/all/libraries/leaflet/leaflet.js you should be able to append this to your sites URL to load the file.

Have you looked through https://www.drupal.org/node/1954942 to see whether anything helps?


Retrieve reference to content type in preprocess I have a content type (let's name it Wheel for an example) that have a field referencing an other content type (which could be Car, Motorbike, Bicycle ...).
So a node named WheelMotorbikeBrand whould reference the content type Motorbike.
I would like to retrieve the value of this field in a preprocess with something like $node->get('field_wheel-type') but I'm not able to obtain a value.
How can I retrieve the value of my field ?

try :

$value = $node->get('field_wheel-type')->getValue();


How to filter content in views based on user id Is there a way to for a normal user (without admin power) to set permissions for a specific piece of content (not a content type) so that it is only visible to a specific user? I want it so that said specific user can see content that has been specifically assigned to them in a table in a view.

You can do it by using these modules:

If you want to give permissions to node then you can use this module

Node Access

  Nodeaccess is a Drupal access control module which provides view, edit
  and delete access to nodes. Users with the 'grant node permissions'
  permission will have a grant tab on node pages which allows them to
  grant access to that node by user or role. Administrators can set
  default access controls per content type, and also define which roles
  are available to grant permissions to on the node grants tab.

If you want to "assign" node to some user, you can use user reference field and then in view add filter for that field and make it filter by current user.

For user reference use this field

References

  There were a couple changes in the way 'References' views are handled
  ("referenceable nodes/users defined by a view"), which might require
  double-checking those existing on your site:

  The 'label' (node title or user name) is no longer automatically    added if not included in the view. If some of your 'References' views
  currently do not include it, you might want to add it explicitly,
  else it will no longer appear in the widgets.
  The HTML generated by the view is no longer stripped out before being    handed to "checkboxes / radios" widgets, thus allowing
  advanced    formatting. You might want to check for Reference views
  having fields    configured to display "as links", since the (probably
  unwanted)     tags generated by Views are not removed anymore.


views_get_view() Memory Exhuasted Im trying the following to bring up a view that only has 6 product nodes, and I get a WSOD with a Memory Exhausted warning, ive set it to 256MB, it shouldnt be flaking out on such a small request!

$view = views_get_view('products');
$view->set_display('Master');
$view->get_title();
$response = $view->preview('block');
dpm($response);

Am i doing something wrong?

Views is notoriously heavy with memory, but it does seem odd that a view that only touches 6 nodes would crap out at 256 MB.

I see you've got a dpm call there - does removing that and turning off the devel module make a difference? And do you have xdebug enabled or any other profiling enabled by any chance? All that stuff would contribute.

The other thing you might want to double check from phpinfo() is to see if your memory limit really is set to 256MB.


Rename "-none-" option for select list field type I have several list fields, one of which is a list (text) field. The default value for the form, where no value is stored if nothing is selected, is "-None-". Is there some way to alter this to say "-Select-" instead? The reason is that in the context of the field, the option of "-None-" doesn't make any sense. In this particular field, one of the actual selections being stored in the database is "None". Here's images of a few fields where -None- doesn't make any sense.

So, is there any way to change these aside from making them required fields?

Implement hook_form_alter() or hook_form_FORM_ID_alter() and use the following code:

$form['field_name'][LANGUAGE_NONE]['#options']['_none'] = t('Select');

example:

function MODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    $form['field_name'][LANGUAGE_NONE]['#options']['_none'] = t('Select');
}

The t() function is for translation.  It may not be required, but it is good practice to use instead of hard-coded strings.

To remove - None - as a choice all together, you could unset the key using hook_form_alter as well.

example:

function MODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    unset($form['field_name'][LANGUAGE_NONE]['#options']['_none']);
}

If you're not using it already, be sure to install the Devel module so you have access to the dpm() and dd() functions.  They are incredibly valuable when playing with Drupal forms.


How to Add Image Field in CIVICRM I am trying to add an Image as Custom field in Civicrm Contact, but the Image Field type is not in the Custom Field section. It has only Field type as File.

How to apply Drupal Image styles for Images uploaded on Civicrm Contact.

I have integrated Civicrm in Drupal 7.

Well if you want a Drupaly solution you could try installing the CiviCRM Entity module along with the Views in Contact Pages module

With CiviCRM Entity you can add Drupal fields to CiviCRM entities, so you could add you a normal Drupal image field and get all the wonderful goodies Drupal provides such as image styles.

Now this field data would live in Drupal field table not in CiviCRM custom field tables.

You add your field on the CiviCRM Entity Contact entity Manage Fields page at admin/structure/civicrm-entity/civicrm_contact

If you can live with the data being in the Drupal DB, not the CiviCRM db, then this can work for you.

Then if you want to display the image on the CiviCRM backend admin contact summary page, you use the Views in Contact Pages module to create a view that displays the image, along with any other data you want, and put that view either as a tab on the contact page, or a pane on the Summary tab.


Inserting "sponsored content" into a fixed position in a view So this is an interesting scenario I'm faced with.  Lets say I have a content type called Article.  Within that content type there is a term that is tagged as "sponsored."  The content type also holds other tags like Chicago, Seattle, San Fran, Etc.

The View I have built is simply time based and shows a feed based on time published of all articles.  However I want some special functionality for any article that is tagged as "sponsored."  At the moment the feed looks like this...

1) tag

2) tag

3) tag

4) tag

5) tag

6) tag

This means that if an article is tagged as sponsored is simply falls down the list as new articles are added.  What I'd like to have happen instead is always FIX the 2 latest sponsored articles (maybe in a node queue) in the second and fifth position.  All other articles without the sponsored tag would fall off as normal based on time while the sponsored articles would stay.  So you'd get

1) tag

Sponsored

3) tag

4) tag

Sponsored

6)

Can this even be done in views?  Should I just think about adding it to the view template file in a custom manor?  Thanks

I found a pretty great solution that i hope others can use.  I simply made a new view with my list of sponsored content in a node queue.  I then used the function views_embed_view inside my view template of content and displayed each block at a certain row ID whick looked a bit like this:

<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
<?php print $row; ?>
 </div>
 <?php if ($id == 3): ?>
<?php print views_embed_view('sponsored_content','block_1'); ?>
 <?php endif; ?>
 <?php if ($id == 8): ?>
<?php print views_embed_view('sponsored_content','block_2'); ?>
 <?php endif; ?>


User profile field used to filter view? OKay - I'm either brain fading or truly confused (probably both).

I need to filter a view based on the value of a field, but in a unique way. The content type (task) has a field (location) which is also used on the user profile. I need the view to only show those tasks which have the same value as the logged in user in that field. What the *&% am I missing?

may be this will help you
views_conditional

How to use Views Conditional in your Views:

Create a view. Add some fields under "FIELDS".
Click on "ADD" next to fields. Scroll down to "Views: Views Conditional", probably found near the bottom of the list.
Add and configure fields
Choose a field to run a condition against, and provide values accordingly.
Save, views conditional handles the logic and returns as specified.
use replacement variables


Set and Get $form_state with ajax button submit function? In my case, I need to get a list of config files to show in a form element. Extending from this Drupal Answers Q/A using form_state->set() inside ajax callback but cannot get the value back outside the callback, I see a suggested way of calling a static function in the submit.

However, I am missing some understanding of how to properly execute.

$list = '';

$form['fieldset'] = [
  '#type' => 'fieldset',
  '#prefix' => '
',
  '#suffix' => '
',
];

$form['fieldset']['list'] = [
  '#type' => 'item',
  '#title' => t('List'),
  '#description' => $list,
];

$form['fieldset']['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#submit' => [static::class, 'customFunction'],
  '#ajax' => [
    'callback' => '::customCallback',
    'wrapper' => 'wrapper',
  ],
];

public function customCallback(array &$form, FormStateInterface $form_state) {
  $list = $form_state->get('list');
  $form_state->setRebuild(TRUE);
}

public static function customFunction(array &$form, FormStateInterface $form_state) {
  $form_state->set('list', $li);
}

How does one get $form_state value into a form element from an ajax button submit function?

Update:

Here is what I have working for this case thanks to @No Sssweat.

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

  $form['fieldset']['list'] = [
    '#type' => 'item',
    '#title' => t('List'),
    '#description' => '',
  ];

  $form['fieldset']['submit'] = [
    '#type' => 'submit',
    '#value' => $this->t('Submit'),
    '#submit' => [static::class, 'customFunction'],
    '#ajax' => [
      'callback' => '::customCallback',
      'wrapper' => 'wrapper',
    ],
  ];

}

public function customCallback(array &$form, FormStateInterface $form_state) {

  $values = $form_state->getValues();
  $li = [];
  $config_path = drupal_get_path('module', $values['fieldset']['module_name']) . $values['fieldset']['directory_path'];

  if (is_dir($config_path)) {
    if ($dh = opendir($config_path)) {
      while (($fileName = readdir($dh)) !== false) {
        if (pathinfo($fileName, PATHINFO_EXTENSION) == 'yml') {
          $fileName = str_replace('.yml', '', $fileName);
          $li[] = $fileName;
        }
      }
      closedir($dh);
    }
  }

  $markup = new TranslatableMarkup(
    '
@li
', [
      '@li' => t('
' . implode('

', $li) . '
'),
    ]
  );

  $form['fieldset']['list']['#description'] = $markup;
  return $form['fieldset'];
}

public static function customFunction(array &$form, FormStateInterface $form_state) {
  // Empty.
}

But this avoids the question as asked.

Should be:

public function customCallback(array &$form, FormStateInterface $form_state) {
  $list = $form_state->get('list');
  $form['fieldset']['list']['#description'] = $list;
  return $form['fieldset'];
}


Views Page Title Based on URL I have a view that has a generic title, but uses contextual filters to show the data. I would like to contextually update the title, but am not seeing a solution to this. Is this possible?

Page URL: /person/jon-doe/roster

Page Title: Jon Doe (based on %2)

Since you're using Views and the user name. All you need to do is:

Add a Contextual Filter, User: Name
Under it's settings pane, under WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED, check Override title
Then just input %2

So now /person/jon-doe/roster would display as jon-doe as the page title.
If you would want the user's normal name like Jon Doe, then you could follow Immanuel Paul's answer because you aren't basing the page title literally from the URL.


Settings vs Code: Can I turn off Broadcast Message through settings? I manage a Drupal Commons site (that relies heavily on OG). I've a request to turn off the ability to broadcast to groups. Is there a box that somewhere that I can un-check or is it better to use hook_menu_alter() in a custom theme to disable the og/users/%/invite path?

Well, I can do this via hook_menu_alter():

if (variable_get('custom_no_broadcast', true)) {
  unset($items['node/%/broadcast']);
}

And in I take the link out via hook_preprocess_block():

// If set, attempts to surpess the link to broadcast messages to all group members.
if (variable_get('custom_no_broadcast', true)) {
    $variables['block']->content  = preg_replace("/<a\shref=\"\/node\/\d+\/broadcast\">Broadcast message<\/a>/", '', $variables['block']->
}

Or just turn off the Commons Notifications module.


how to display avatar in forum-list (advanced-forum) Any suggestions? I'm interested in how to display the avatar last post in forum list. I tried to display the avatar as $picture but is not working.

You may include the picture of the author of the forum topic by configuring the corresponding view:

admin/build/views/edit/advanced_forum_topic_list

HTH


How to skip (don't update) some fields from existing node during import if this field already has a value? I'm using drupal 7, feeds 7.x-2.0-alpha8. How to skip (don't update) some fields from existing node during import if this field already has a value?

i.e. We periodically import some products with photo (create new and update existing). After that editor can change photo. How can I skip this photo field during next update?

There is some feeds tamper plugin to check is field in updating node is empty? Maybe there is some hook from feeds or feeds tamper?

Had the same problem. I finally used hook_feeds_presave(), and unset the field I wanted to skip. Here's the code:

function mymodule_feeds_presave (FeedsSource $source, $entity, $item, $entity_id) {
  if ($source->importer->id == 'myimporter'){
    // I check if my imported value is equal to a special marker i set
    if ($entity->my_field['und'][0]['value'] == 'MARKER') {
      unset($entity->field_i_wanted_to_skip);
    }
  }
}

This automatically resets THAT FIELD ONLY. Hope this helps someone.


remove node options from admin area when creating nodes where creating nodes (node/add/content-type) bellow body box there are some options related to comments, author, menu and ..

How can I hide those options?

You need to create a module and implement hook_form_alter.

Then, in the $form array, unset the array index(es) containing the parts you don't want your users to see and configure.

ps: I advice you do the above by permissions. So, those array indexes are unset for specific roles not all roles which would include user#1


Webform Submission & Commerce Order Database Relations Where is the relation between Webform Submission ID & Commerce Order ID in the drupal database?

The problem is one of my orders crashes after editing the webform so I guess that the relation between the order and the webform crashes in the database.

I've seen commerce_ and webform_ tables but I didn't find anything.

Check out table: field_data_commerce_webform_sid
it contains webform submission ID and entity_id (for commerce_line_item)

Then use table: field_data_commerce_line_items to find the commerce_order id for a specific commerce_line_item ID.


taxonomy tokens throwing invalid token error I have a drupal 7 site, any time I use a token with taxonomy term in it, I am getting the error,

The Default path pattern for Product (applies to all Product content types with blank patterns below) is using the following invalid tokens: [term:name].

for example [term:name] or [term:description]

Look at http://drupalcontrib.org/api/drupal/contributions!token!token.module/function/token_element_validate/7. Implement hook_form_alter() of form you are trying to submit and look for #element_validate array key, in field you get an error should be

  '#element_validate' => array('token_element_validate'),

Then you should check  #token_types key value. It can have any value, as examples:

 '#token_types' => array('node'),

OR

 '#token_types' => array('all'),

In my case I got similar error in metatag_context module when I was trying to save taxonomy token into metatags context field. Problem was in '#token_types', they was empty, I added array('all') value and form works fine.


How to programmatically add a facet to Facet API based on returned facet values? I would like to programmatically and conditionally show a facet block, if the returned values match some certain criteria. I have not found any solutions so far.
For example, if a facet returns 25 apples, I would like to show an additional facet that does some calculation on this value.

If you used Search API, this code should help you:

$delta = facetapi_hash_delta(facetapi_build_delta('search_api@INDEX_MACHINE_NAME', 'block', FACET_NAME));
print render(module_invoke('facetapi', 'block_view', $delta));


How do I add extra/custom plugins in CKEditor? I am copying the templates plugin http://ckeditor.com/addon/templates
I put    it in my D8 folder /core/asstes/vendor/ckeditor/plugins
I do a 'drush    cr'

I do not see the templates plugin under available buttons in my text format

How do I get the templates plugin to show up?

You have to build a plugin in Drupal using the CKEditor classes in the CKEditor module in core, it is not an automatic integration.

Check some of the existing modules that integrate plugins for examples on how to do this.

Checkout:

CodeSnippet
Color Button
Panel Button


Setup different pager settings for same view Is there a way to display the same view with different pager configurations? For example have the same set up with 3 items for the homepage and full paged for a news list page? Thanks!

I dont think its possible, you can achieve this by adding another page/block display to an existing view and specify the pager values accordingly.

As Ursula said, When you change your pager on the second display, do not forget to change the 'for' pulldown menu on the modal window from 'all displays' to 'this page (overwrite)'. Otherwise, you changed the pager for all displays.


How to retrieve view row attributes when in twig template I am using addClass() in hook_preprocess_views_view_unformatted (see my question regarding this at here), and the class is added to each row, but the next stop for the view results is views_view.html.twig, where dumping the rows data with
{{ dd(rows) }}

shows no sign of the attributes part of the row data, which contains the class.

The views-view.html.twig template is at a higher level. To manipulate data at that level, you'll need to use template_preprocess_views_view().
You used template_preprocess_views_view_unformatted() which allows you to manipulate the data in views-view-unformatted.html.twig. This seems like the correct approach given your case.
Here are the contents of views-view-unformatted.html.twig from the views module in core.
{#
/**
 * @file
 * Default theme implementation to display a view of unformatted rows.
 *
 * Available variables:
 * - title: The title of this group of rows. May be empty.
 * - rows: A list of the view's row items.
 *   - attributes: The row's HTML attributes.
 *   - content: The row's content.
 * - view: The view object.
 * - default_row_class: A flag indicating whether default classes should be
 *   used on rows.
 *
 * @see template_preprocess_views_view_unformatted()
 *
 * @ingroup themeable
 */
#}
{% if title %}
  <h3>{{ title }}</h3>
{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{- row.content -}}
  </div>
{% endfor %}

You can see that if you loop through the rows variable, each row has an attributes property - the classes you added in template_preprocess_views_view_unformatted() will be part of it.


How can I allow all users to access only a certain type of entityform? I need that all users (anonymous users too) have access to the submissions of a certain type of entityform.

I can set the permission View any entityform submission and it works but for all types of entityform. I also try with hook_access

How can I allow all users to access only a certain type of entityform but not for all types of entityform?

In filter. Just add.

  content: type => is one of (put check mark on all those content types
  you want. )

And then add permission for that view.

The another way is.

Go to permission section under people admin menu.
Navigate to node section.
You will find your content type name with VIEW,EDIT,DELETE permission
with each users.
Just put check mark for the user you want to them able too see.

Hope this will work.


Memcached - Saving Custom Array I have the memcache module installed on Drupal 7. While it works fine I would like to implement some custom caching in some of my modules. For example, if I want to store the array:

$data = array('hi'=>1,'bye'=>2);

I can normally do the following:

$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_set($memcache_obj, 'var_key', $data, 0, 30);

How can I do the equivalent in Drupal using the memcache module. I am trying to avoid having to declare the $memcache_obj each time and just use the one designated by the module.

With Drupal you are not supposed to manage the cache backend by yourself. Once memcached is set as your cache backend, you can just use the cache functions cache_set(), cache_get(), etc. and this data will go to cache.


The Expanding & Folding of the information related to a checkbox isn't working in drupal 7.34 I am using Drupal-7.34, and after enabling the following modules:

Admin-Menu.
Ctools.
IMCE.
IMCE Wysiwyg Bridge.
insert.
jquery-Update.
Libraries.
Link.
Pathauto.
Token.
Views.
Wysiwyg.
Webform.

I got a problem about the "Expanding & Folding of the information related to a check box"

For Example:
After enabling all the modules listed above, when I enter into the configuration of the "View UI" Module and try to "Add a view"; And after checking/unchecking the check boxes of "Description", "Create a Page View" or "Create a Block View", the information related to these check boxes is not expanded or folded. (Just the mark of checking/unchecking will appear/disappear and nothing else happen.

Note that before enabling the following modules listed above, this problem didn't appear and everything was great...

any help will be appreciated, Thank you in advance.

IN THE IMAGE BELOW, YOU CAN NOTICE HOT THE DESCRIPTION CHECK BOX IS CHECKED BUT THE TEXT BOX TO WRITE A DESCRIPTION ISN'T APPEAR AND ALSO HOW THE CREATE A PAGE CHECK BOX IS UNCHECKED BUT ALL THE INFORMATION RELATED TO IT STILL APPEARED AND DIDN'T DISAPPEAR OR FOLD...

I had a similar issue back in August. It was the jQuery update module that was the problem.  The configuration at this link finally worked for me: https://www.drupal.org/node/1810656#comment-8677587


Path-based context and URL aliases - wrong block shown My (Drupal 7) site has a search which uses two blocks - one for entering the criteria and one for the results.

(For brevity, I won't explain in detail why I need two blocks but it's basically because I'm doing a drop-down search a bit like this approach.  Suffice to say that I can't do it all in one block.)

The search is at mysite.com/contact-us.  I've got a context rule which shows the criteria block in the sidebar when the contact-us URL path matches.

I want the results block to appear on the same page as the criteria block, appearing in its place.  Therefore, I've got a URL alias of contact-us/find, which points to contact-us.  My context rules say that if the path is contact-us/find, the results block should be shown.  (The alias was set up via the UI, i.e. Configuration > URL aliases)

So both contact-us and contact-us/find show the Contact Us page, but there are different Context rules and so different blocks are shown in the sidebar.

That's the theory anyway.  Here's what happens in practice:

I browse to mysite.com/contact-us.  I see the criteria block.
I fill in the search criteria
I am taken to e.g. mysite.com/contact-us/find?property=35 (the querystring provides an ID which the results view uses).  I see the results block in the sidebar.  So far, so good!
However, if I then go back to mysite.com/contact-us (e.g. to search again), I still see the results block and not the criteria one!  And it thinks there are no results as I no longer have the querystring.

If I clear the cache, all is well again - I see the correct blocks.  But I need a solution which doesn't require a cache clear - that's not something my users will be doing!

I presume that I'm running into problems because both contact-us and contact-us/find are actually the same node, and so Context can't accurately differentiate between them unless the cache is empty, but I'm not sure.

Any suggestions how I could resolve this one?  Could I have a different type of rule specifying when the blocks should appear?  Or something else?  I'm all out of ideas!

In the end, we changed the whole approach here, and made the jump menu load the new block with AJAX.  (I wasn't the person who developed the new way of doing this, so I can't provide much more detail, I'm afraid.)  This was a lot less buggy than my original approach!