Difference between content type and content entity What is the difference between content type and content entity?

Content Types are one of the main building blocks within a Drupal site; as the name suggests, content types hold content. However, different content types can hold different kinds of content; an event can hold information that is specific to a time, where a discussion can be used for people to talk. Most sites have multiple different content types, and the name of a content type will ideally give information about how it is used.

An Entity is a piece of data within a Drupal site. Nodes, users, comments, and taxonomy are all entities; additionally, with custom code, you can create new entity types if/when needed. You can also add fields to entities, which allows for things like detailed user profiles, or more sophisticated comment forms.


Display term description below a field widget based on the selected option on node edit form I am trying to show a block (or the term description) on the node edit form when a user selects the term.

An example:

User is creating a node with a "location" vocabulary. They select their state (parent term), then a region in the state. A block or the term description will display directly below the dropdown for the parent term (their chosen state). If they select another state, another block or term description will come up for that state.

Basically each term in the vocabulary will have subtle but different submissions guidelines and I would like to inform the user during the node creation process as to the guidelines for each state.

I am not sure if I should create a "state submission guidelines" content type then Entity Reference it, build a view and embed it or try to get the term description or another field attached to the term to show. How does one make dynamic node edit forms?

I am running Drupal 7, Display Suite, Views, CSHS, Rules as the main stack.

EDIT: I am also using Conditional Fields if that can be utilized.

Thanks.

You can add an #ajax property to the state field in a hook_form_alter() and then include the taxonomy term description as a form item below the state field if state is set.
See the ajax examples in the examples module or post here is you have any problems.

I don't think there is any need to use a block.


How to hide authoring information on webform for Drupal 7 I went to Administration > Structure > Content Types > Webform > Manage Display where I am supposed to find a check box to hide or display author information but there is nothing there. Any idea how I could hide this?

Thank you for your thoughts

Drupal 7
Webform 3

The author/date display is controlled in the edit form for the Webform content type, at http://mysite.com/admin/structure/types/manage/webform.

The checkbox you're looking for is here:


Creating a full site package I found that the ST Conch theme has a full site installation package with that theme.

How do I go about doing this? And would it be possible to populate the database with the data as well...?

Thanks

What you are wanting to create is a Drupal Installation Profile. This is a method of packaging together multiple Drupal contributed modules and/or themes, plus potentially custom code and functionality, into a neat package that can be distributed and installed with the same resulting "full" website every time.

You'll want to refer to the drupal.org documentation on building installation profiles to get the basics behind how this is done.

Also very helpful will be the Features module. Features allows you to easily package together different sets of Drupal configurations, such as content types, views, and system variables. There are many different documentation and tutorial resources for Features. This is a good video tutorial on the basic concepts of Features.

There are a lot of additional extensions for Features that will help you package additional items into a Feature, such as node content, taxonomy terms, theme settings, etc.

In addition, some of the work you want to do in your installation profile (re: "populate the database with the data as well...") may need to be executed within custom code - either a custom module or as part of your installation profile's install tasks and/or install script. You can even set up a form to allow users to choose from a set of options during the installation.


Path field not available in Search API View Why is the "Path" field not available in a Search API view? Is there another way to get the path for each row in this type of view?

\/organize$

\/: forward slash escaped

organize: letters "organize" matches the characters "organize" case sensitive.

$: Must be the end of the string.

Regex101


How much data is ok to put in the global $user object or $_SESSION variables? I'm building a site and there are some pieces of information that I am going to use constantly.  My thinking is that instead of making a ton of database calls, that I would put some of these critical pieces of info in the $user object or $_SESSION variables.  The question is, however, how much is too much info in these variables?  Which should I use?

It's hard to put a limit on things like this. But if you have more than a few pieces of data related to the user, you should probably put it in a table of it own. You can add the data to the user when loaded, and the performance hit will only be a few ms, not measurable really. You will make things easier on yourself by being able to query the data instead of having it stored as serialized data.

One thing to note about $_SESSION is that it should only be used for storing temporary data. A use case could be storing the values entered in a form, to let the user pick up from where he left, if he moves away from the form and comes back later.


Rewrite Link to taxonomy page in Views I am using views to show a list of items from a vocabulary, I want a link under each item to the friendly url for the full view. Currently I am using the rewrite results in views like this:

Find out more about [name]

How can I get the friendly url that is setup in pathauto i.e. /partners/google?

You can set

Find out more about [name]

(without the anchor tag) in Rewrite the output of this field, and then use the Output this field as a link option and set that to

taxonomy/term/[tid]

Views will rewrite the link according to Url Alias settings.


Install a PDF maker to the panel of a WYSIWYG editor? After installing WYSIWYG and CKeditor how can I install some kind of PDF maker to the panel of the editor?

I don't know of a pre-built solution for this.
I assume you want a PDF icon similar to what there is in MSWord or OpenOffice.

There is no PDF generation capability with client-side Javascript that I am aware of, so it would be difficult to implement something like this in the browser.

There are plenty of server-side PDF solutions, however, but you'd have to send the editor content back to the server somehow (AJAX), and then have the PDF generated and sent back to the client.

There looks to be some discussion of this at the CKSource forums.

It might be easier to just use the Print module.


How can I save parts of the URL to the database when a certain page is viewed? Can a page be created the normal way (not by module) in Drupal 7, using Content Type an so forth, yet still trigger a module and pass a variable from the URL.
The idea is to let the web team create their page as normal, but require the last part of the path to be a variable. Then a module is called to take that variable and do magic with it.
We want the module to work with the variable in the background, NOT render a page.

Marketing creates the page with a URL that contains a variable
representing the user. User gets an email and clicks on button that
goes to page. When they get to the page the module is triggered to
collect the variable data from the URL. The module will then save that
value to a DB.

Use template_preprocess_node
Have the URL in the e-mail formatted like this:
example.com/node/1?param1=value1?param2=value2

If it's required that the user must be logged in
example.com/user/login?destination=node/1?param1=value1?param2=value2

I used /node/1 as an example, but you can use its url alias instead if it has one.
Then in your mymodule.module file
function mymodule_preprocess_node(&$variables) {
  $node = $variables['node'];
   if ($node->type == 'article') { // checks its Article Content Type
     $params = drupal_get_query_parameters();
     if (!empty($params)) {
       // do more magic to get each param value on its own
       // save to the DB
     }
   }
}


Create map that show user Location and last user's post I don't know my question is cheap or good !:(

I want to create a map that shows on users location and last post like Azadnegar's map or Drupal.org front page.
I know I should use openLayers, CCK, views but I can't build as well as Azadnegar!
I want to know how create map like its map, I mean how can I config our modules.
in this site get user location in registration form in list box,how create like it?

what map her use?How create views?or ...

please explain whit detail !

Once I had to do the very same thing and followed this good video by Drupal Therapy. It uses GMap (API 2) + Location modules instead of Open Layers, but if you're on D6 this is still a good solution. If you enable user-locations and node-locations functionalities in the modules page, you'll find predefined Gmap user/nodes location views. If you need to associate geographic information only on certain content types (and not to all nodes), you'd better enable location-CCK and just add and configure a location field to your desired content type, then create your Gmap view.

Hope it helps you to start with maps in Drupal.


Views Dependent Filter showing when no controller value selected I'm using Views Dependent Filters to have a filter show based on the value of a filter above it. It is working for the most part but it is showing the field by default (when no controller value is selected.)

When my multiple select filter  being used as the controller, the dependent field shows even when no value is selected. For example:

Vehicle:

Car (Set as controller)
Boat
Plane

Tire Size (Dependent Filter)

Small
Med
Large

Tire size shows when "car" is selected but also shows when no value is selected. I believe this the module is not intended to function this way.

Is there a solution to this or a possible alternative?

This was a bug relating the default views multiple select filter. I used the Better Exposed Filters checkboxes and now the dependent filter works as intended.


Authcache vulnerabilities? In my experience Authcache gives a great enhancement to performance, however I am wondering what are the potential vulnerabilities using authcache and boost together? My worry is that when the administrator does not exclude user specific paths in boost configs, a saavy user can somehow access to other users' cookies and do nasty things.

I guess it is not just a hypothesis, as I've seen that at least in one occasion in a boost+authcache+varnish arrangement a user reported that others have sent message on her part without her knowledge. If this indicate a real security hole, how should one counter int? Which paths should be absolutely excluded from being cached by boost?

What other potential security holes can be in this setting and how to avoid them?

Long term I would take a look at ESI over authcache. Not sure when manarth will get a stable release of 7.x out. ESI has fairly strong security with rotating keys and things like that.


Hide form behind PayPal payment The site I'm working on at the moment has a competition that requires the following workflow:

User creates an account
User pays fee with PayPal (ideally a button)
User enters multi step/page form

I'm at a loss as how to best implement this:

The Webform Paypal module allows me to include a button but when I put it on the first page of my form it doesn't redirect me back to continuing the rest of the submission after payment.

The Payment for Webform module has too many steps:

First you have to click 'add payment' which opens a new window
Then you have to select a quantity
Then you have to select a payment method
Then you're taken off site

The Webform Paymethod Select module has the same issue as the first module except I get a 404 after completing a payment.

I'm wondering if payment should be part of the form at all? Is it possible to hide the webform until a successful payment has been received? I guess I'd have to write something custom for that.

What I ended up doing was creating a separate page with a generated PayPal button. You can include a hidden field called 'custom' that you can use to pass in your own data so I included the current user's UID. After a successful payment you can get PayPal to send a POST with the details to a URL of your choosing. I set up a custom page with a listener then updated the user account specified by the UID.


How do I override the $message value of the UniqueFieldConstraint class? I am new to Drupal 8 and I have added Core Constraint called "UniqueField" on my custom field "Customer_no" which is attached user to Entity. Below is that code which I am trying to override error Message but its not working:

  function devel_reg_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {

      if ($entity_type->id() == 'user' && isset($fields['field_customer_number_reseller_i'])) {

        $fields['field_custome_no']->addConstraint('UniqueField', []);
        //The below code not setting Custom Error Message
        UniqueFieldConstraint::$message = "Custom Error Message";
      }
    }

The message is hard-coded into UniqueFieldConstraint. It's a public property, so there may be a way to set it that I don't know about. However, another way to go about it is to extend UniqueFieldConstraint, set your own message, and tell the system to use your class instead of the original.

Extend the class:

namespace Drupal\[MODULE]\Plugin\Validation\Constraint;

use Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldConstraint;

class [MODULE]UniqueFieldConstraint extends UniqueFieldConstraint {
  public $message = 'Something about an @entity_type with a @field_name and value of %value.';
}

Implement hook_validation_constraint_alter() to swap out the existing constraint for yours:

function [MODULE]_validation_constraint_alter(array &$definitions) {
  $definitions['UniqueField']['class'] = '\\Drupal\\[MODULE]\\Validator\\Constraints\\[MODULE]UniqueFieldConstraint';
}

Note that [MODULE] should be swapped out with the appropriate value, and the class should be placed in the appropriate folder for the given namespace.

Update: Or, as 4k4 mentioned, you can add @Constraint annotation to the  constraint above, creating a new constraint. This new constraint can then be explicitly attached to whatever it is that needs constraining.

Which method to use will depend on whether you want to override the UniqueFieldConstraint message any time it is called (the original method I outlined) or whether you want to explicitly attach the constraint to specific items (4k4's method).


I can't login to Drupal as my session cookie was deleted? I'm using Drupal 7, and have Pound running in front of Varnish for HTTPS.  I can browse the site via HTTPS, but can't login - each time I do, the server returns a 403 forbidden error.  Any ideas as to what is causing this?  I'm guessing something may need to be changed in settings.php, but not sure.

Output from Firebug:

POST user

Response Headers

Accept-Ranges   bytes
Age 0
Cache-Control   no-cache, must-revalidate, post-check=0, pre-check=0
Connection  keep-alive
Content-Length  0
Content-Type    text/html; charset=UTF-8
Date    Tue, 09 Oct 2012 17:49:08 GMT
Etag    "1349804948"
Expires Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified   Tue, 09 Oct 2012 17:49:08 +0000
Location    https://drupal.domain.com/user/2
Server  Apache
Set-Cookie SESSe15687525d17b8ec181665a71c88775c=EttXyyPvqESdU4RapW7xZkrRagGNHgRH5I9P6x0yRRE; expires=Thu, 01-Nov-2012 21:22:28 GMT; path=/; domain=.drupal.domain.com; httponly SSESSe15687525d17b8ec181665a71c88775c=mAdWa_a_OvcIIoWBuiVbLqFJzwyHiukfd_xBOVz_eaQ; expires=Thu, 01-Nov-2012 21:22:28 GMT; path=/; domain=.drupal.domain.com; secure; HttpOnly
Via 1.1 varnish
X-Drupal-Cache  MISS
X-Varnish   2081364495

Request Headers

Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-us,en;q=0.5
Connection  keep-alive
Cookie  has_js=1; __utma=194497400.1529654640.1349804906.1349804906.1349804906.1; __utmb=194497400.3.10.1349804906; __utmc=194497400; __utmz=194497400.1349804906.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
DNT 1
Host    drupal.domain.com
Referer https://drupal.domain.com/user
User-Agent  Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0.1

GET 2

Response Headers

HTTP/1.1 403 Forbidden
Server: Apache
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified: Tue, 09 Oct 2012 17:49:08 +0000
Cache-Control: public, max-age=300
Etag: "1349804948-1"
Content-Language: en
X-Generator: Drupal 7 (http://drupal.org)
Set-Cookie: SSESSe15687525d17b8ec181665a71c88775c=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=.drupal.domain.com; secure; httponly
SESSe15687525d17b8ec181665a71c88775c=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=.drupal.domain.com; httponly
Vary: Cookie,Accept-Encoding
Content-Encoding: gzip
Content-Type: text/html; charset=utf-8
Content-Length: 8916
Accept-Ranges: bytes
Date: Tue, 09 Oct 2012 17:49:09 GMT
X-Varnish: 2081364496
Age: 0
Via: 1.1 varnish
Connection: keep-alive

Request Headers

GET /user/2 HTTP/1.1
Host: drupal.domain.com
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Referer: https://drupal.domain.com/user
Cookie: has_js=1; __utma=194497400.1529654640.1349804906.1349804906.1349804906.1; __utmb=194497400.3.10.1349804906; __utmc=194497400; __utmz=194497400.1349804906.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); SESSe15687525d17b8ec181665a71c88775c=EttXyyPvqESdU4RapW7xZkrRagGNHgRH5I9P6x0yRRE; SSESSe15687525d17b8ec181665a71c88775c=mAdWa_a_OvcIIoWBuiVbLqFJzwyHiukfd_xBOVz_eaQ

Pound passes along the client IP appropriately, but it needs to be forcibly set for non-https (http) requests to Varnish.

if (req.http.X-Forwarded-Proto !~ "https") {
  remove req.http.X-Forwarded-For;
  set req.http.X-Forwarded-For = client.ip;
}


Failed to load popup dialog with in views I am using Drupal 8.6.1 with the 8.x-1.0-alpha2 Footable module and the core dialog.

What I did so far:

Install the Footable module.
Download the most recent 3.x.x version of the FooTable jQuery plugin from https://github.com/fooplugins/FooTable/tags and move the contents of the compiled directory into the libraries/footable directory.
I have created a simple "footable" views showing all articles with below fields:

Title (Title)
Body (Body)
Image (Image)
Tags (Tags)

Configured the footable settings to hide the below element on any device:

Body (Body)
Image (Image)
Tags (Tags)

So far, the footable view is working just as expected without no error at all.

Here is an image:

Now, I want when I click on the title field, a dialog popup will open displaying me the contents of the /node/{{ node:nid }} in that popup so:

Under the advanced Section, Set the Use Ajax to: Yes
Add the Content: ID to the footable view but excluded form the display.
Edit the title field:

Uncheck the "Link to the Content" box.
Check the "Override the output of this field with custom text" box.
Add this line of code: {{ title }}

Now, If I visit the Footbale view page, the footable is working prefectly but when I click on any title, the
entire page will refresh and redirect me to /node/{{ nid }} path with no any dialog poping up.

Am I missing something here in my configuration ?!

NOTE:

If I change the view display from Footable to any other display like for example the built-in Table, the dialog will popup without any issues at all.

Thank you,

After further Google search I found this Webform issue.

Solution:

You have to use the Footable dev version and not the alpha2 version.


Create user without password using rest api From this documentation, currently what the User Registration resource does is to register a user that requires password in the Rest API.

Our goal is to call/use this api endpoint http://localhost:8080/user/register?_format=json to create a user once validated via facebook and dont want to have password in the json.

This is what Im getting when tried to remove the pass field

{
    "message": "No password provided."
}

from

{
"name": { "value": "test03" },
"mail": { "value": "test03@gmail.com" }
}

Just like when you create a user on user/register, the visibility/requiredness of the password field depends on the verify_mail setting.

If e-mail verification is enabled, then you must not provide a password, if disabled, you must provide one.


Update the number of comments without refreshing the cache I am running a local installation of Drupal 7 with the Disqus module installed.

I have created a view with a list of "blog" nodes, and the number of comments displaying through the view. The number of comments in my view does not refresh/update without clearing the cache in Drupal.

Is there a specific way to do this for Disqus, or automatically refresh the Drupal cache?

Long story short, you need ESI or AJAX to do what you want.

This will help you get there, but I don't believe any of the below modules will do exactly what you're looking for.
http://drupal.org/project/esi
http://drupal.org/project/ajaxblocks


Updating content to remove it from the front page shows it as being 'New' I am removing content from the front page as it is out dated, but I don't want to un-publish it as it remains valid information.

Unfortunately Drupal then labels the old article as 'New' and put it to the top of the content list, exactly the opposite effect of the one intended.

How can I stop this?

You should "uncheck" the checkbox "promoted to the frontpage" (which is shown when you 'edit' such nodes). That way it will not be shown on the frontpage anymore.


Remove trimmed version form preview screen? When I preview a node before creating it I get this message:

'The trimmed version of your post shows what your post looks like when promoted to the main page or when exported for syndication. You can insert the delimiter "<!--break-->" (without the quotes) to fine-tune where your post gets split.'

And I also get a trimmed and full version in the preview. This has no relivance for my site and is actually quite confusing. How can I remove it?

I dont want to hide the message with CSS (as in the linked method) as im assuming other messages can be shown in the same div.
How to hide the "trimmed version" from the preview page?

Ive tried removing the teaser display for the content type under 'custom display settings'.

The field is a text area, not a text area with summary.

Ive tried using the String Overrides module.

Ive tried this theme function but it didnt do anything.
http://drupal.org/node/1355962

Ah, the linked template.php override method (code below) does work but you need a sub theme for it to do so.

/**
 * Override node preview to remove trimmed teaser version.
 */
function theme_node_preview($variables) {
  $node = $variables['node'];

  $output = '
';

  $preview_trimmed_version = FALSE;

  $elements = node_view(clone $node, 'teaser');
  $trimmed = drupal_render($elements);
  $elements = node_view($node, 'full');
  $full = drupal_render($elements);

  // Do we need to preview trimmed version of post as well as full version?
  if ($trimmed != $full) {
   // drupal_set_message(t('The trimmed version of your post shows what your post looks like when promoted to the main page or when exported for syndication. You can insert the delimiter "&lt;!--break--&gt;" (without the quotes) to fine-tune where your post gets split.'));
    //$output .= '
' . t('Preview trimmed version') . '
';
    //$output .= $trimmed;
    //$output .= '
' . t('Preview full version') . '
';
    $output .= $full;
  }
  else {
    $output .= $full;
  }
  $output .= "
\n";

  return $output;
}

UPDATE this has stopped working for me. It seems the code doenst work properly with my zen template.

UPDATE This code worked for me:

            /**
             * Returns HTML for a node preview for display during node creation and editing.
             *
             * @param $variables
             *   An associative array containing:
             *   - node: The node object which is being previewed.
             *
             * @ingroup themeable
             */
            function THEMENAME_node_preview($variables) {
              $node = $variables['node'];

              $output = '
';

              $preview_trimmed_version = FALSE;

              $elements = node_view(clone $node, 'teaser');
              $trimmed = drupal_render($elements);
              $elements = node_view($node, 'full');
              $full = drupal_render($elements);

              // Do we need to preview trimmed version of post as well as full version?
              if ($trimmed != $full) {
               // drupal_set_message(t('The trimmed version of your post shows what your post looks like when promoted to the main page or when exported for syndication. You can insert the delimiter "&lt;!--break--&gt;" (without the quotes) to fine-tune where your post gets split.'));
               // $output .= '
' . t('Preview trimmed version') . '
';
               // $output .= $trimmed;
               // $output .= '
' . t('Preview full version') . '
';
                $output .= $full;
              }
              else {
                $output .= $full;
              }
              $output .= "
\n";

              return $output;
            }


Can I edit theme CSS without FTP access to the files? Can I edit Drupal theme CSS files with out the ability to download/upload css files using FTP?

Without server access of some description either via FTP or SSH (for example) - you can't edit the files.

You could, however, try CSS Injector if you are able to install modules through the UI.

  Allows administrators to inject CSS into the page output based on
  configurable rules. It's useful for adding simple CSS tweaks without
  modifying a site's official theme -- for example, a 'nighttime' color
  scheme could be added during certain hours. The CSS is added using
  Drupal's standard drupal_add_css() function and respects page caching,
  etc.


How to create a page showing certain roles? I want to create a page that shows the organisation of the group behind the website. To do this, I would like to render a list of certain Drupal roles, along with every user that has that role. However, I have no idea how to do this without writing a custom module. Is there a way?

Create a view (using Views module) of users with a grouping by role. You can add a filter for the specific roles that you want to include.


Need real help on this module I'm really need a good documentation or some kind of HowTo for Google Font module,i installed it and i choosed my Google font and what after? i m asking if i need to do some manual css or php work or just some other configuration in the GUI .
Thank you very much

As the module page desription says development of this module has been stopped in favour of @font-your-face

@font-your-face is widely used now and has decent documentation, so you should use this one instead of Google font.

Module page description,

  IMPORTANT: I've decided to combine forces with @sreynen, the
  maintainer of the magnificent @font-your-face module. That modules
  does not only support Google Fonts, but also several other font
  providers and combines all those fonts in a very user-friendly
  interface. I will not improve the Google Fonts API module anymore. So
  please switch your site to (the 7.x-2.x version of) @font-your-face in
  favor of Google Fonts. Thanks ;)


custom user page image field crashes when uploading, removing image I am loading user form with this code

   $account = user_load($user->uid);
  module_load_include('inc', 'user', 'user.pages');
  $userform = drupal_get_form('user_profile_form', $account);
  return drupal_render($userform);

I have a image field in the form and i'm altering form to append another template file

function customuserprofile_form_alter(&$form, &$form_state, $form_id, $account = 'account') {
  switch ($form_id) {
    case 'user_profile_form':

 $form['#theme'] = 'custom_profile_form';

and i am printing this field in custom-profile-form.tpl.php

<div class="field1"><?php print drupal_render($form['field_profile3'])    ?> </div>

it is ok that code is showing me image field but when i click upload or remove button in image field i get this error

Notice: Undefined index: user_profile_form in drupal_retrieve_form() (line 760 of Z:\home\drupaler.uz\www\includes\form.inc).
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'user_profile_form' not found or invalid function name in drupal_retrieve_form() (line 795 of Z:\home\drupaler.uz\www\includes\form.inc).
Notice: Undefined index: #user_category in block_form_user_profile_form_alter() (line 563 of Z:\home\drupaler.uz\www\modules\block\block.module).
Notice: Undefined index: #user in ckeditor_user_customize() (line 41 of Z:\home\drupaler.uz\www\sites\all\modules\ckeditor\includes\ckeditor.user.inc).
Notice: Trying to get property of non-object in ckeditor_user_customize() (line 41 of Z:\home\drupaler.uz\www\sites\all\modules\ckeditor\includes\ckeditor.user.inc).
Notice: Undefined index: #user_category in system_form_user_profile_form_alter() (line 1954 of Z:\home\drupaler.uz\www\modules\system\system.module).
Notice: Undefined index: field_profile in file_ajax_upload() (line 271 of Z:\home\drupaler.uz\www\modules\file\file.module).
Notice: Undefined index: #suffix in file_ajax_upload() (line 280 of Z:\home\drupaler.uz\www\modules\file\file.module).

problem is that image field works uncorrectly with in my page. but it is ok in /user/1/edit page Maybe ajax in uploading, removing image needs some corrections or any hacks? Please help me I'm in trouble!

In the menu entry for your custom page, if you have not already done so, you need to add the file path and file to reference the user module files, like so...

$items['my/custom/page'] = array(
    'title' => 'My Title',
    'page callback' => 'my_page_function',
    'access callback' => TRUE,
    'file path' => drupal_get_path('module', 'user'),
    'file' => 'user.pages.inc',
  );

I find it's necessary to include the reference in the function, as you have already done, and also include it in the menu entry.  Don't forget to clear the Drupal cache after updating the menu entry.


How do I override the Bootstrap3 user registration form? I am trying to override the default user registration form (user_register_form). I would like for the form to create a CCK node (membership_request) that is already on the system. I am able to get all of the hook overrides setup correctly but I can not get the fields of the CCK form to show up.

Here is what I have done so far:

sites/all/themes/bootstrap/includes/registry.inc

 $hooks['membership_request_node_form'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('theme', 'bootstrap') . '/templates/forms',
        'template' => 'node--membership-request-form',
        'arguments' => array('form' => NULL),
        'preprocess functions' => array(
                'bootstrap_preprocess_membership_request_node_form'
        )
  );

sites/all/themes/bootstrap/template.php

function bootstrap_preprocess_membership_request_node_form(&$vars) {
    //$args = func_get_args();
    //array_shift($args);
    //$form_state['build_info']['args'] = $args;
    //$vars['form'] = drupal_build_form('membership_request_node_form', $form_state['build_info']['args']);
    //$vars['form'] = drupal_build_form('membership_request_node_form', membership_request_node_form(array()));
    $vars['intro_text'] = t('This is my super awesome reg form');
}

sites/all/themes/bootstrap/templates/forms/node--membership-request-form.tpl.php

<?php
print $intro_text;
//print drupal_render_children($form);
?>

In the below examples, "This is my super awesome reg form" will show up as expected  in the new registration form. However, 1) all attempts to pass the form from the preprocess function have failed for me (as shown with the commented lines in the template.php file) 2) when the drupal_render_children line is uncommented in the tpl file I get the following errors:

Thanks

Why don't you alter the user registration form by adding fields at admin/config/people/accounts/fields there is an option Display on user registration form.

This will then modify the User entity to use those fields, which may mean your membership_request node is not needed, but if it still is you can use Rules to automatically create a node when a user registers.


Prevent underscores from removing text? Drupal seems to be removing all text prior to an underscore in my form. This is in the Form.php file of my module implementing Google CSE, so I cannot change the attribute name.

if (array_key_exists('search_broadness', $get_results) && $get_results['search_broadness'] == 'narrow') {
  $block .= 'data-as_sitesearch="' . $gcse_narrow_search_query . '"';
}
$form['search']['results'] = array(
  '#type' => 'item',
  '#markup' => $block,
  '#allowed_tags' => ['script', 'div'],
)

And this is the output, note that the data-as_sitesearch is shortened to sitesearch.

The Drupal Google CSE module does not have this feature, so I cannot use that. #markup in Drupal 7 worked to get around this, but not in Drupal 8. Is there a workaround to bypass this sanitation?

I'm struggling to understand what that code is trying to do; I'm assuming your end goal is to render either this:

Or this, if the condition passes:

But I don't see how the code sample would ever to get to even the result in your question. There's no mention of a
, and if $block contains the opening
 'html_tag',
  '#tag' => 'div',
  '#attributes' => ['class' => ['gcse-searchresults-only']],
  '#value' => '',
];

if (array_key_exists('search_broadness', $get_results) && $get_results['search_broadness'] == 'narrow') {
  $form['search']['results']['#attributes']['data-as_sitesearch'] = $gcse_narrow_search_query;
}


How to force a dev release of my module? Whenever I go to create a release for my contrib module, it gives me one option - 6.x-1.x (6.x-1.x-dev) - but if I select that it says "The version you have selected (6.x-1.x-dev) is already in use by another release." IIRC dev releases are packaged automatically every twelve hours, so why is this option even appearing? And it seems like dev releases aren't being packaged automatically for my module ...

In the "Release" tab of your project you've a checkbox with "Show snapshot release". If you check it, you should see the dev releases appear.


Move file in Drupal 6 I am using drupal 6 as i am trying to save file that comes from another server through Json format

I am using

file_move('path of image','sites/default/files');

I also tried this  one Still having same error

file_move('path of image','sites/default/files', $replace = FILE_EXISTS_RENAME));

But it gives this error

  Fatal error: Only variables can be passed by reference in

How to solve this? Anybody have idea ?

Thanks

Your First argument must be a variable. The file_move() documentation says:

  $source: Either a string specifying the file location of the original file or an object containing a 'filepath' property. This parameter is passed by reference and will contain the resulting destination filename in case of success.


Making a block to show the status of the user account? How do I use a Views block (or other means) to show the status of the user account, specifically awaiting approval, approved, and not approved ?

Pending User Notification Block

  This module is for sites that allow users to create an account, but
  require administrator approval for account activation. This module
  creates a block that shows a list of unactivated user accounts, with
  links to their account pages. This block is visible for anyone with
  'administer users' permission, and will not be shown to any other
  users.


How do I print out a specific node to my page? I'd just like to print out the body of a specific node (no title or other fields).  Am I doing this right?

echo node_load(127)->body['und'][0]['value']

I can't seem to find the answer in any of the Drupal docs.

Looking with the Devel module to the structure of a loaded node, I notice that "body" contains the following values:

The first array index is the language ID for the language set for the node; it could be also LANGUAGE_NONE (the string "und") for nodes for which the language is set to "neutral." That array index contains an array with the following indexes:

"value": the content of the "body" field
"summary": what set as summary (or teaser) for the node
"format": the input format associated with the "body" field

In the node I used as example, if you try accessing $node->body['und'][0]['value'], you would access an undefined value. You should use $node->language to know the language set for the node; you code should be similar to the following one:

$node = node_load(127);
$body = $node->body[$node->language][0]['value'];

As for printing the body content, the "body" field contains the text before the input filter is applied; you should use code similar to the following one, to print the "body" field:

$node = node_load(127);
$language = $node->language;
print check_markup($node->body[$language][0]['value'], $node->body[$language][0]['format'], $language);


What could cause uids to not be numbered consecutively? I just noticed something weird in a site I'm working on. The first account is user/1 as usual. A second account I created two weeks later is user/20, and a third one a couple days later is user/32. Etc. Two accounts I just created right after each other are numbered consecutively as expected.

There are no custom modules modifying the registration process or anything. I wonder what could cause this, and if there's something I need to fix.

So, it turns out this is indeed normal since Drupal 7: the users table is not auto-increment but uids are created with a sequences API that is shared with actions and batch jobs. Uids can therefore be non-consecutive.

Several reasons for changing back from auto-increment table in D6 are pointed out here by chx.

(From reading chx's response to this blog post)


Getiing error during email send process I am using PepiPost mail service for sending an email. PepiPost mail service provides an SDK for send sending mail. They provided a sample code for sending mail.

When I send the mail getting the following error message:

  Unable to send e-mail. Contact the site administrator if the problem
  persists.

But mail is sent to the corresponding user and user can receive the mail.

I have created a Custom mail system call by implementing
MailSystemInterface. The code is available in the here. Although this is the code I placed in mail()  function.

class TestMailSystem implements MailSystemInterface {
  require_once __DIR__.'/includes/vendor/autoload.php';

  use PepipostAPIV10Lib\Controllers\Email;

  public function format(array $message) {
    // Join message array.
    $message['body'] = implode("\n\n", $message['body']);
    return $message;
  }

public function mail(array $message) {

$email = new Email();

$data = array(
      'api_key'   =>  '************',
      'recipients'    =>  $message['to'],
      'email_details' => array(
        'from'          =>  $message['from'],
        'subject'       =>  $message['subject'],
        'content'       =>  $message['body'],
        'fromname'      =>  $message['fromname'],
        'tags'          =>  'test',
        'replytoid'     =>  $replyto,
      ),
      'X-APIHEADER' => array('UserID1','UserID2'),
      'settings' => array(
        'footer'        =>  true,
        'clicktrack'    =>  true,
        'opentrack'     =>  true,
      ),
    $response = $email->sendJson( $data );
}

}

When I send the mail getting the following error message:

  Unable to send e-mail. Contact the site administrator if the problem
  persists.

User receives the email. What would the reason for the error message be?

MailSystemInterface::mail has a particular return value:

  TRUE if the mail was successfully accepted for delivery, otherwise FALSE.

The caller uses that to determine whether or not the mail was sent successfully, so just return TRUE when the mail succeeds and the error will stop.


View Module : How to display list of Taxonomy terms with record count I cloned the default Glossary view and changed it a bit to look like something as following:

A (3)
C (7)
D (10)
E (12)
...

But instead of Alphabets, how do I make it show taxonomy terms, for example:

General Knowledge (24)
Inspirational Stories (20)
Current Issues (10)

Appreciated...

Drupal 7

With View 7.x-3, you first remove the "Content: Title" contextual filter, and then you add the "Content: Has taxonomy term ID" one.

In the dialog for the settings that appear once you select the context filter, you set the options as in the following screenshot. There are two displays: "Page," and "Attachment"; the first screenshot is for "Page."

The result is the following view; the first screenshot show the output when none of the links have been clicked on.

Drupal 6

In Views 6.x-3, the used terminology and the user interface change, but the steps to follow are similar.

Also in this case, there are two displays, which have the same name used in Views 7.x-3; differently from Views 7.x-3, the display to change are the default one, and "Attachment."

You first remove the "Node title" argument, and add the "Taxonomy: Term ID" argument; the first image is for the default display.

In the latter display, the argument will be displayed as list by default; I didn't change it.

Important: There are two similar contextual filters/arguments, where in one appears the word "depth"; the difference is that this last contextual filter/argument shows all the node where the taxonomy term is the select one, or one of its children. You should use this one, if the vocabulary is organized hierarchical, and for example, the taxonomy terms are "Porsche," "Porsche >> Carrera," and "Porsche >> Cayenne"; in this case, selecting "Porsche" will show also the nodes using  "Porsche >> Carrera" and "Porsche >> Cayenne."


How do I change the position of "sidebar first" for the Arabic version of website? Can I change the position of the "sidebar first" if I change the website language?

More Details: My default website language is now English, and my "sidebar first" is in left position. This is what I want: to change the position of the "sidebar first" if I make the website in the Arabic language.

Install the Context module.

  Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.

Make sure that Multilingual select which is part of the Internationalization module is also installed (this will provide the proper condition).

You can now create a new context that has a condition of 'Language' and a reaction of 'Blocks'.

You will create a condition-reaction pair for two cases. First for all the LTR languages, second for all the RTL languages.

Allthough this does not directly answer your question as to regions, you can play around with the reactions, such as template suggestions etc to achieve your objective.


How to get the default value of radio button from database? I have 5 check-box. For each check-box, 5 radio buttons get generated. These radios value get saved to database. Now what I want is, when I select check-box, and if the selected check-box has some database value already saved in database, that radio button should show saved database value, mean to say, it should be shown selected.
5 check-box are like:
1. A
2. B
3. C
4. D
5. C

All check-box has radio options like:
Male or Female

If(say) I choose "Male" for "A" and submit my form. when I again go to that form and choose "A", "male" radio button should be shown selected.

some code implementation:

foreach ($check-box-options as $key => $value) {

        $form['radio_'.$key] = array(
            '#type' => 'radios',
            '#title' => t('abc'),
            '#options' => $filter_radio_options,
            '#default_value'=> ???,
            '#states' => array(
                'visible' => array(
                    ':input[name="filter_criteria_options['.$key.']"]' => array('checked' => TRUE),
                ),
            ),
        );
}

$check-box-options is an array of check-box A,B,C,D,E. For each check-box, I have radios.

$serialized = unserialize($radio_buttons_database_values);

$serialized contains all selected radio button values. If I replace $check-box-options with $serialized, I got correct radio button selected as default, but if I loop $serialized as nested inside $check-box-options, it is throwing last selected value from database for every check-box. I am not getting the exact problem with my code or approach.

Can anyone please help me understanding the exact problem behind this?

As the radios are separate field in itself, default value should be as easy as follow

foreach ($check-box-options as $key => $value) {
        //A. A function to query database to get default value
        $default_value = _my_module_helper_get_default_radio_option($key);

        //B. Or if its a system setting form, all values are inside the variables, in that case all you have to do is variable_get()
        $default_value = variable_get('radio_'.$key);

        // Depending on form type use option A or B.

        $form['radio_'.$key] = array(
            '#type' => 'radios',
            '#title' => t('abc'),
            '#options' => $filter_radio_options,
            '#default_value'=> $default_value,
            '#states' => array(
                'visible' => array(
                    ':input[name="filter_criteria_options['.$key.']"]' => array('checked' => TRUE),
                ),
            ),
        );
}

// In case option A is what you needed.
function _my_module_helper_get_default_radio_option($key) {
  return db_select('your_table','yt')
         ->fields('yt',array('field_name'))
         ->condition('yt.field_is',$key,'=')
         ->exectue()
         ->fetchField();

 }


Field collections data not being saved I am working on a website which has many Entity forms and some of the Entity form has field collection with few fields in it and it allows multiple items "Unlimited". When you save the node, the data does not save. When you click 'add new item', it also doesn't save the data, it just creates a new set of empty fields and has a 'remove' button.

after pressing submit button the form save all the data apart from data which is in Field collection.

After some research I come to know that Entity forms is not a good option for forms which has more them 100 Fields, because after 100 Fields the form creation become very slow.

one of the Entity forms in website has 180 Fields I am not sure if it is causing the problem.

There is no error message in logs, server error log and Firbug.

After some research I come to know that is not a good option for a big project due to performance, Field collection can be quite annoying from a performance perspective.

There are alternative ways to achieve a better result.

1 - Composed Field worked for me and improved system performance

2 - Creating a new content type to represent collection and then using Inline Entity Form to allow creation of the collection inside of the content type referencing it.

3- Using Multifield. however data extract could be a pain.


Return data from WebformHandler to Controller I created WebformHandler where I need to get data entered in the form on submit. It's something like this:

<?php

namespace Drupal\xxx\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Form submission handler.
 *
 *
 * @WebformHandler(
 *   id = "xxx",
 *   label = @Translation("xxxx"),
 *   category = @Translation("xxx"),
 *   description = @Translation("xxx"),
 *   cardinality =
 *       \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results =
 *    \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */
class XxXx extends WebformHandlerBase {

  public function confirmForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    $values = $webform_submission->getData();
    // Get data here
  }
}

I also have the Controller and defined route with template file. Controller looks like this:

<?php

namespace Drupal\xxx\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\xxx\Plugin\WebformHandler;

/**
 * Class SearchFlightsController.
 */
class XxXController extends ControllerBase {

  /**
   * xXx.
   *
   * @return array
   *   Return search parameters string.
   */
  public function xXx() {

    return [
      '#theme' => 'xxx',
      '#search_query' => $this->t('Test Value'),
    ];

  }

}

My question is how to pass the data that I get in WebformHandler on form submit to Controller that need to show the page with defined route?

I don't know why you want to pass the data to the controller, you can do anything with the data in the webformhandler code. or you can pass the data using the namespace declared on the controller. please check the following code.
Inside the controller file place the below code that I have added new function to handle the webform data.

namespace Drupal\xxx\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\xxx\Plugin\WebformHandler;

/**
 * Class SearchFlightsController.
 */
class XxXController extends ControllerBase {

  /**
   * xXx.
   *
   * @return array
   *   Return search parameters string.
   */
  public function xXx() {

    return [
      '#theme' => 'xxx',
      '#search_query' => $this->t('Test Value'),
    ];

  }

  public function getwebform($formdata){
      /** place your code what want to do with $formdata*/
  }

}

//After that inside the webformhandler code write the following code
 /** take the data from webform and save in an array variable $formdata then pass to the function defined inside the controller */

use Drupal\xxx\Controller\XxXController;
$webfrmdata = new  XxXController;
$webfrmdata->getwebform($formdata);

I have not tested but hope this code can help you


Cannot figure out what's wrong with my schema It keep saying

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

Here is my Schema:

function artx_partner_schema() {
  $schema = array();

  $schema['artx_partner'] = array(
    'description' => 'The base table for artx_partner.',
    'fields' => array(
      'partner_id' => array(
        'description' => 'The primary identifier for a partnership.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'uid' => array(
        'description' => 'User identifier.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'nid' => array(
        'description' => 'Node identifier.',
        'type' => 'int',
        'not null' => FALSE,
      ),
      'product_id' => array(
        'description' => 'Identifier for a product.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'reqtime' => array(
        'description' => 'time stamp of the request',
        'type' => 'datetime:normal',
        'mysql_type' => 'datetime',
        'unsigned' => TRUE,
        'not null' => FALSE,
      ),
      'restime' => array(
        'description' => 'time stamp of the response to request',
        'type' => 'datetime:normal',
        'mysql_type' => 'datetime',
        'unsigned' => TRUE,
        'not null' => FALSE,
      ),
      'status' => array(
        'description' => 'the status of the request, pending(0)/AC(1)/Rej(2)',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'primary key' => array('partner_id'),
    'unique keys' => array('unique' => array('uid', 'nid', 'product_id')),
    'foreign keys' => array(
      'owner' => array(
        'table' => 'users',
        'columns' => array('uid' => 'uid'),
      ),
      'product_display' => array(
        'table' => 'node',
        'columns' => array('nid' => 'nid'),
      ),
      'product' => array(
        'table' => 'commerce_product',
        'columns' => array('product_id' => 'product_id'),
      ),
    ),
  );

  return $schema;
}

Unsigned attribute is not supported with datetime. Following code will create table for you.

function artx_partner_schema() {
  $schema = array();
  $schema['artx_partner'] = array(
    'description' => 'The base table for artx_partner.',
    'fields' => array(
      'partner_id' => array(
        'description' => 'The primary identifier for a partnership.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'uid' => array(
        'description' => 'User identifier.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'nid' => array(
        'description' => 'Node identifier.',
        'type' => 'int',
        'not null' => FALSE,
      ),
      'product_id' => array(
        'description' => 'Identifier for a product.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'reqtime' => array(
        'description' => 'time stamp of the request',
        'type' => 'datetime:normal',
        'mysql_type' => 'datetime',
        'not null' => FALSE,
      ),
      'restime' => array(
        'description' => 'time stamp of the response to request',
        'type' => 'datetime:normal',
        'mysql_type' => 'datetime',
        'not null' => FALSE,
      ),
      'status' => array(
        'description' => 'the status of the request, pending(0)/AC(1)/Rej(2)',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'primary key' => array('partner_id'),
    'unique keys' => array('unique' => array('uid', 'nid', 'product_id')),
    'foreign keys' => array(
      'owner' => array(
        'table' => 'users',
        'columns' => array('uid' => 'uid'),
      ),
      'product_display' => array(
        'table' => 'node',
        'columns' => array('nid' => 'nid'),
      ),
      'product' => array(
        'table' => 'commerce_product',
        'columns' => array('product_id' => 'product_id'),
      ),
    ),
  );
  return $schema;
}


Ajax views (watch) table I want to have a table view that remains on a particular page, but once someone anywhere on that site creates a node that is a part of that view, the view updates through AJAX and I see the new entry. Like a live twitter feed but for nodes.

Found it!: module Views Auto-Refresh, which used to be part of the Views Hacks module (but is now considered a "Graduated module", as mentioned on the project page). `Here are some details about it, i.e. a quote from its project page:

... to refresh a view after a specified time interval. Includes advanced options to avoid reloading the whole view, and to avoid causing a full Drupal bootstrap at each refresh.
Suitable for usage on liveblogs, activity streams, comment lists, and any other view where new items are frequently added.


Webform textarea character counter I want to add a character counter on a textarea field on Webform.
I tried the Maxlength module but it doesn't work (I can't find any reference to it on editing the field) and I read it works only for content types, not Webform.

Then I installed  Webform Countdown and added this code to my sites/all/libraries/word-and-character-counter/word-and-character-counter.js (Yes, I installed Libraries Module as well) but I don't really know what should I do now. Am I supposed to see something about it on editing the field? I can't find anything.

I'm also using Webform Validation and limiting the max lenght of my textarea fields. It's working fine but I also need something to count the chars as the user is typing.

Can anyone please help me? What's the best solution for this?

Thank you in advance!!

https://www.drupal.org/project/webform_countdown
Provides a textarea component for Drupal webforms with a configurable, twitter-style dynamic word or character count.


How to get the current path, keeping the langcode? For my button I need to specify the destination path, as my site is multilingual it is imporatnt for me to keep the langcode in the path. So how can I get from

 drupal-site/fr/page_1

to

 drupal-site/fr/page-2 ?

By just appending /page-2 I lose my language settings.

You can try code:

$langcode ='en';
$node_url = $node->getTranslation($langcode)->toUrl('canonical', ['absolute' => TRUE])->toString();


Printing views exposed sort criteria separately to exposed filters Exposed filters are either:
- Printed in views-view.tpl.php using the $exposed variable.
- Printed in a block, probably using the same variable.

This variable ($exposed) contains the exposed sort criteria and filters. I would like to find a way to print them separately. Ideally there would be  a way to use something like:

<?php print $exposed->sort; ?>

<?php print $exposed->filter; ?>

Does anyone know of a way you can achieve this? Or in last case how to print each sort and criteria individually?

If you can not use each item of $widgets in separated way, you can push each widget in a separated array for use each widget across your custom html.

<?php foreach($widgets as $id => $widget): ?>
    <?php
    array_push($elements, $widget);
    ?>
<?php endforeach; ?>

<?php
echo $elements[0]->widget;
echo $elements[1]->widget;
//etc
?>


uid = 0 for all kinds of users I want to get the uid of a logged in user in an external php script. I am using:

chdir("C:/xampp/htdocs/mywebsite");
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$account1 = user_uid_optional_load();
echo $account1;

But it always return :

  stdClass Object ( [uid] => 0 [name] => [pass] => [mail] => [mode] => 0
  [sort] => 0 [threshold] => 0 [theme] => [signature] =>
  [signature_format] => 0 [created] => 0 [access] => 0 [login] => 0
  [status] => 0 [timezone] => [language] => [picture] => [init] =>
  [data] => [roles] => Array ( [1] => anonymous user ) )

irrespective of admin, authenticated or anonymous user. I also tried these but the result remains same.

global $user;
echo $user;

$account1 = user_load(array('name' => check_plain($name)));
 echo $account1;

I also checked a similar problem and uncommented $cookie_domain = ''; ( blank cookie domain for localhost )in my settings.php but to no avail. How can I get some non-zero uid for logged in users ?

Because you need to login from external script...  Your external script is always anonymous to Drupal since no session has been created for external script user....

If you are trying to load all online users in an external script you can check who's online block implementation in user module..


Use Zen grids with Views We are using Zen 7.x-5.x with responsive settings and I want to create a grid for some items. That is responsive and adaptive so first the grid is 3 items and then when the viewport gets narrower there is 2 or one.

How can I use Zen grids with Views is there an automatic way of specifying a n column(s) responsive grid out of views? Is there a connection or are there any specific classes I can use in my views?

Thanks!

You can create grids inside the main container or others.

You can look at these 2 modules for views and grids:

Views Responsive Grids

Views Column Class

Then you only need to create your own grid for that view. And of course you can select n columns with nth-child

For example: A view with Views Responsive Grids of 3 columns and N rows

  .your-view-class {
  $zen-column-count:  3;
  @include zen-grid-container();
  div:nth-child(n+1) {
    .views-column-1 { @include zen-clear(); @include zen-grid-item(1, 1);}
    .views-column-2 { @include zen-grid-item(1, 2);}
    .views-column-3 { @include zen-grid-item(1, 3);}
  }

}


How to create a drag & drop sorting interface programmatically? If you have seen the Views module, there is "sorting criteria", where we add fields and then rearrange fields to set the priority. In order to rearrange, we click on "rearrange" link and all fields get a draggable UI so that we can move it up or down to set sorting priority.

How can I do this thing exactly programmatically?

Here is a drupal_add_tabledrag function using which you can add draggable functionality programmatically.

  Assists in adding the tableDrag JavaScript behavior to a themed table.

  Draggable tables should be used wherever an outline or list of
  sortable items needs to be arranged by an end-user. Draggable tables
  are very flexible and can manipulate the value of form elements placed
  within individual columns.

See this blog for example. You may need to imprement theme function.

$element = $vars['element'];
drupal_add_tabledrag('sample_table', 'order', 'sibling', 'item-row-weight');

$header = array(
  'label' => t('Attribute'),
  'checkbox' => t('Enabled/disabled'),
  'weight' => t('Weight'),
);


Create Database Table in Run Time I have an SQL CREATE TABLE.

CREATE TABLE myid_template_1
(
template_id int NOT NULL,
template_description character varying NOT NULL,

);

I want to know its equivalent query structure in Drupal 7 to create tables at run time. I tried the code below, which it didn't return any error. I wonder if it successfully creates a table, since I could not find the location of the table I created.

function myid_create_db_fields(){
    $template_id = 1;
    $schema['myid_template_'. $template_id] = array(
        'description' => t ('Contains a particular templates data inputted from the MyID Inputting System'),
        'fields' => array(
           'template_id' => array(
               'type' => 'int',
               'not null' => TRUE,
           ),
           'template_description' => array(
               'type' => 'character varying'
               'not null' => TRUE,
           )
        ),
    );
    db_create_table('myid_template_' . $template_id, $schema);
}

PS: I don't want to use hook_schema() because the table is not created when the module is installed.

You're passing the wrong thing as the schema definition.

This is what you need:

$schema['myid_template_'. $template_id] = array(...);

db_create_table('myid_template_' . $template_id, $schema['myid_template_'. $template_id);


Implementation of PDF generation I am working on a requirement where I have a link "get report". When User clicks it, the information is fetched from DB and a PDF report is generated. Finally the PDF file will be shown to the User to download or view in browser. I want to know what is the better way of implementing the link, onclick functionality. Do I have to use Ajax module or something else. Please help.

That should prove easy to do with Views PDF. It is easily customisable compared to other PDF modules.
However if you're planning yo do complex reports that is one thing drupal doesn't excel in.


Refresh [account:one-time-login-url] I have a module that creates a new user and automatically logs

//set up the user fields
$fields = array(
  'name' => $login,
  'mail' => $to_insert['email'],
  'pass' => user_password(10),
  'status' => 1,
  'init' => $to_insert['email'],
  'timezone' => 'Europe/Paris',
  'roles' => array(
     DRUPAL_AUTHENTICATED_RID => 'authenticated user',
  ),
);

//the first parameter is left blank so a new user is created
$user = user_save('', $fields);
user_login_finalize();

However, I want to create a rule to send the information to the new user.
I would use the token [account: one-time-login-url] but it does not work.

What for?
How to refresh this token when I create a new user?

Thanks for your help

You can handle this very easily in your module. Once you save the account and you have the user object just simply use _user_mail_notify(). As an example:

 _user_mail_notify('password_reset', $account);

If you want to alter the email in any way you can do that with hook_mail_alter() from within your custom module.


What mapping solution do people use that has a proximity filter? For D6 I used gmap, which allowed me to easily create map-based views and include proximity filters and sorts. With D7 I've been tempted to move to OpenLayers - I like the idea of learning one powerful mapping tool that can be used to solve more problems than presumably gmap could. However I can't for the life of me find anything that looks close to stable for proximity filters and sorts. I find this a bit surprising - does anyone know of anything I've missed? The best lead I've found so far is this sandbox project, but I haven't given it a go yet.

So can anyone recommend a way, with or without OpenLayers, to have Views-based mapping and proximity filters on D7?

As of writing this, jpstrikesback's sandbox: Proximity is really solid. I have it running on a few production sites without issues. Once he feels it's 100% it is either going to be released as the D7 version of OpenLayers Proximity or use the new namespace "Proximity" (as it really does not require OpenLayers to function).

I recently wrote up a walkthrough of how to get this up and running for another question on stack exchange. See Need a simple Google Maps solution; lost in the labyrinth of modules.

As you mentioned GMap was ok in D6, but using OpenLayers is much more robust and flexible. It's worth spending the extra time to get it set up. Good luck


How to create queue for email sending I am using PepiPost mail service and I created custom mail system class for integrating PepiPost service. I can successfully send email from Drupal site. If a connection timeout 504 occurs during email sending process, email is not triggered how can I handle this scenairo. This is the code I used for email sending

class CustomMailSystem implements MailSystemInterface {

  public function format(array $message) {
    // Join message array.

      $message['body'] = implode("\n\n", $message['body']);
      return $message;
  }

  /**
   * Implement mail method to send mail via Sendgrid.
   *
   * @param array $message
   * @return bool
   */
  public function mail(array $message) {
    $email = new Email();

    $data = array(
      'api_key'   =>  '****************',
      'recipients'    =>  $to
      'email_details' => array(
        'from'          =>  $from,
        'subject'       =>  $subject,
        'content'       =>  $body,
    ),

  try {
    $response = $email->sendJson( $data );

  catch(Exception $e){
      print 'Call failed due to unhandled exception/error('. $e->getMessage().')'."\n";
    }
  }
}

you should always use some or the other Mail Transfer Agent (MTA) like Postfix, which helps in managing queue in-case of emails getting lost


Custom node access, need to rebuild permissions for each content item created I have a module that handles node access to a custom content type with hook_node_access. Basically, an anonymous user needs to enter a passcode to view the page. Currently, I'm doing this through session variables. If they have $_SESSION['example'] set, return NODE_ACCESS_IGNORE, otherwise

drupal_goto('form');
return NODE_ACCESS_DENY;

Currently, after I create a new content item, the anonymous user will submit the code, be redirected to the content item, and then get an access denied error.

If I rebuild the permissions, the access will work properly, but not for any content items I create after the rebuild.

The Content Access module is enabled on the site. Testing locally, I have tested both disabled (not uninstalled) and enabled content access module and access is currently working as intended.

It seems like your problem matches the following:

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

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

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

Good luck, let us know how this goes!


Prevent Quick Editing on certain DOM elements I want to enable quick edit within a block which contains some JS libraries (such as slick). As slick changes the DOM, when I use quick edit it saves this altered DOM and then the slick library doesn't work.

Simplified example:

Saved HTML (pre-page load)

Tile 1

Tile 2

Rendered HTML (page loaded)

Tile 1

Tile 2

As the slick JS code adds the extra DOM content, when the user saves something via quick edit, the extra DOM content is saved to the page. Subsequently, when slick is rendered again by the JS, we get a slider that doesn't work.

Is there a way to prevent quick edit from applying changes to anything within
? Alternatively, is there a place where I can use slick's destroy method to the object before the block changes to edit mode?

Note:

Have tried using Bootstrap's carousel which doesn't alter the DOM but the functionality is too limited to match what slick can provide

Edit:

The JS object resides within a block. I still need to use quick edit to edit the block, but also to protect the JS object

Is there a way to prevent quick edit from applying changes to anything
  within

A quick fix is you can write a small jQuery snippet which gets trigger after QuickEdit apply its DOM changes. For example, suppose I do not want to allow quickedit on any node, i.e. it can be full display or teaser. Below code will find all article tags on page and remove its data-quickedit-entity-id attribute, so quickedit option won't be available for it.

$('article', context).removeAttr('data-quickedit-entity-id');


How to give to the users the opportunity to change role as desired As the title says, I would give to members a way to choose their own role as required via radio buttons in their profile page. Any suggestion?

You can do this with rules.

Event: After saving user profile
Conditonal: field has value
Action: Assign role to user

Something long these lines. You will need to create a new rule for each role unless you do some special field-value handling. You will also need to create a few checks in here to prevent the rule from re-assigning a role to a user.


Identical permission set for panels and panelizer with different results I have a brand new site install profile I'm working on and with a clean site install, I'm seeing different results of the same permission setting. We have roles "Site Editor" and "Site Admin" and for panels and panelizer, all permissions are set identically. However, Site Admin is seeing all Settings, Context, Layout, Content, and Breadcrumbs. Site Editor is seeing what should be seen: Layout and Content. I'm not sure if there is some other hidden permission that a Site Admin has that the Site Editor does not have that is causing this override.

It appears that this is a documented bug in panelizer where a role having "Administer Organic groups permissions" can see all options for panelizer even when those panelizer permissions are not set for that role.


Redirect users from authentication URLs to signup page I'm using Drupal 6.

I want to redirect users from /user/login, /user/register, /user to /sign-up if the user is the anonymous user. This page would show both login and register forms together.

The only page left would be /user/password, which form I don't want to have on /sign-up.
I'm comfortable with PHP, but I'm not sure about which hooks should I use to achieve this.

PS. I already know how to print those forms on my own. My doubt is just about the URLs.

There is no dedicated hook for things like this, but you can implement hook_init() and then do the redirect there. Something like this:

function yourmodule_init() {
  global $user;
  if (in_array($_GET['q'], array('user', 'user/login', 'user/register') && !$user->uid) {
    drupal_goto('sign-up');
  }
}


Workflow - sms/email notifications Is there a way to set up sms/email notifications to be sent out to site users responsible for each workflow stage? Also, is there a way of automatically "assigning" a node to the correct resource for managing the workflow stage?

Check out the rules module. You can set up a rule that accesses other module (search for a sms module), or core features (like mail).


Node Referenced entity fields not showing in views? I have created a content types "author detail and blog content".

In which author detail is having fields

1)author name

2)author picture

3)author designation

4)about author

Then i created a field "author details(node reference field)" in blog content

After creating a view block none of fields of author details(reference entity) is showing and also this block should be contexual filter based.

I have tried to achieve it by reading articles available on internet,Only one field is holding all the fields value ,i want to show field value in such sequence so that i can give specific class to each and every field.

1)author name

2)author picture

3)author designation

4)about author

How to achieve?

For displaying the authors details within a Twig template see How can you render fields from an entity reference in node templates? [Drupal 8] - for creating a views block this page might help you: https://www.drupal.org/node/1841004


How to create a view block only visible to the Referenced Content Type's Author? I have 2 custom content types: Item for sale, and Bid (offer). The latter has a node reference URL to a node of the first content type.

I created a view (block) which shows the people with their offers.

I need to edit this view in such a way that is will be only visible to the person who created the Item for sale (author of the first content type may only see this block).

How can I achieve this? I cant seem to find a way with contextual filters.

Easiest way to do this:

Add a content relationship for the node reference field (i.e. Content: field_item_for_sale_ref)
Add another relationship for the Content Author and select the node reference field relationship from the dropdown list at the top of the window.
Filter the view for the current logged in user by selecting the author relationship that was just created in step 2.

OR

Add a content relationship for the node reference field (i.e. Content: field_item_for_sale_ref)
Add a contextual filter for the Content: Author uid, select the node reference field relationship from the dropdown list (top of window), select: provide default argument of type: user id from logged in user

Either way the result is the same and it's what you need.


How to create Select list on Entity forms with changeable list of key values? I would like to create a field for my Entityform same as 'Select list' with ability to change its values after the data is submitted.

Currently when I am trying to change the default values of 'Select list' it gives me the error:

  Allowed values list: some values are being removed while currently in use.

or:

  There is data for this field in the database. The field settings can no longer be changed.

I believe this behaviour should be different than for Content type, as when using Entityform I don't care for already submitted data (as it's something that suppose to be submitted only once)?

Question

How do I create a Select list widgets on Entity forms where I am able to change its key values once the data has been submitted?

How do I fix or workaround that Drupal limitation, or I should use a different solution/module instead or write my own?

Example scenario

So for example I want to create a Select list widget (e.g. contact_by field) appearing on Entity form which has the following values:

by_phone|By Phone
by_email|By Email
ops_typo|By Post (fixme: correct typo)
by_fax|By Fax (fixme: remove me)

So the critical scenario would be a strong need of changing these values such as typo (correcting ops_typo) or changes in business requirement how these form works (e.g. I want to remove by_fax appearing on the submission forms for new forms), however it is currently not possible by using a standard Select list widget, because it has already some existing data associated with that value

Reproducible steps

Launch Drupal sandbox.
As admin, add a new entityform type (Admin/Structure/Entityform Types/Add) for auth users: Test
Add new required field Contact By of List (text) type as Select list widget pasting above values.
Create two entity forms (Admin/Structure/Entityform Types/Submit Link or at /eform/submit/test), one with By Post, another with By Fax values.
Now go to Manage fields of that Entityform, in 'edit field' or 'field settings' try removing/changing the last two values (the key part, not label).

Data storage

As per comment concern, the change of value won't corrupt any existing data (despite of the warning), because the value in stored is database in the text format anyway, for example:

INSERT INTO `field_data_field_title` VALUES ('entityform','test_title',0,207,207,'und',0,'Foo');
INSERT INTO `field_revision_field_title` VALUES ('entityform','test_title',0,207,207,'und',0,'Foo');

which has the references to the right entityform:

INSERT INTO `entityform` VALUES (208, 'test_title', '', 1447192797, 1447192797, X'733A303A22223B', 1, 0, NULL);

So when viewing the entity form (e.g. /entityform/208) is just showing plain text. I don't need to edit that data, as it's just one-off form submission.

As for workaround, it is possible to use Taxonomy Term Reference field type as Select list, which would provide me a dynamic list of options (list of terms) which can be changed in the future.

However this is not ideal solution for multiple forms from UX perspective, as I have to create a separate taxonomy vocabulary for each widget (or creating a very long one).


Are there any easier ways to update a site than following the official instructions? For tech people (like sys admins) the are the official instructions about How to update Drupal Core for how to update a site. But what if the user is inexperienced and just wants to maintain the site by installing security updates?

I can follow these steps myself but if I'm not available it's important that anyone (in the organization I'm volunteering for) can do it.

So, are there any easier ways to update a Drupal 7 site than following the official instructions?

If you have access to ssh in your server install drush (drupal shell) http://docs.drush.org/en/master/install/

This will only need to be done once and and then it will be easy to apply drupal core updates from the command line

drush up drupal

or any other module updates

drush up views

But I would recommend applying ALL security patches at once (core and modules security updates) using

drush upc --security-only

all the above commands will do all the necessary actions as described in the instructions that you linked above and in case of a bad update the updates are reversed with error messages displayed.

To learn drush read https://www.ostraining.com/blog/drupal/drush/ but the installation instructions might be a little outdated. You can also learn more drush commands at drushcommands.com


How can I dynamically get the fields on an image media bundle? What’s the correct way to get all of the key/values for a bundle on a media entity?

I am trying to create a media entity programmatically and I need to get all of the fields on the image bundle. I am not sure how to get the image bundle ID either.

In other words, I’d like the module I'm working on to be a bit more generic and reusable as I’ve seen the image bundle have different names depending on the installation.

Here’s what I have so far but the two main problems I see are that the image bundle ID can change and the field names on the bundle can be different.

   $entity = $this->createFile(
      $uri,
      $file[0]['filename'],
      $file[0]['filesize'],
      $this->currentUser
    );
    $entity->setPermanent();
    $entity->save();
    // Save media entity
    $media = [
      'bundle' => 'image',
      'uid' => $this->currentUser->id(),
      'status' => 1,
      'image' => [
        'target_id' => $entity->id(),
        'alt' => t(basename($file[0]['filename'])),
        'title' => t(basename($file[0]['filename'])),
      ],
    ];
    $image = $this->entityTypeManager->getStorage('media')->create($media);
    $image->save();

I'd like to be able to get the image bundle and dynamically figure out whichever field has the target_id and then assign the previously created file entity to that. I do not know how to get the image bundle schema, array signature, in order to traverse the key/values to find the target_id

You can traverse the field definitions of the media bundle image and look for a field with the type image:

$fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('media', 'image');
foreach ($fields as $key => $field) {
  if ($field->getType() === 'image') {
    // found image field $key
  }
}

To get all media bundles:

$bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo('media');


Use my existing jquery function in drupal 7 I have my function like this in jquery

$(document).ready(function(){

    // set the map-wrapper width and height to match the img size
    $('#map-wrapper').css({'width':$('#map-wrapper img').width(),
                      'height':$('#map-wrapper img').height()
    })

    for (i=0; i<$(".pin").length; i++)
    {
        // store initial tooltips contents within an array
        var tooltipContent = new Array();
        tooltipContent[i] = $(".pin").eq(i).html();

        // set tooltip direction type - up or down
        var tooltipDirection = 'tooltip-up';
        if ($(".pin").eq(i).hasClass('pin-down'))
        {
            tooltipDirection = 'tooltip-down';
        }

        // append the tooltip
        $("#map-wrapper").append("
\

" + tooltipContent[i] + "
\

");
    }

    // show/hide the tooltip
    $('.tooltip-up, .tooltip-down').mouseenter(function(){
                $(this).children('.tooltip').fadeIn(100);
            }).mouseleave(function(){
                $(this).children('.tooltip').fadeOut(100);
            })
});

But i am unable to use it in Drupal 7 . So what changes do i need to make for it.

Your are missign two important things. First, in Drupal 7 jQuery is namespaced to avoid conflict with other JavaScript libraries. So you should either wrap your code in an anonymous function to assign the jQuery object to the $ variable (ie. (function($){...})(jQuery);) or use jQuery instead of $.

Second, you shouldn't use $(document).ready() but add you code as a the attach function under the Drupal.behaviors.yourModule namespace. Behaviors are attached on the documentobject on load, but also to any new element added to the page by any well behaving scripts (the ones that call Drupal.attachBehaviors()). Finally, because behaviors could be attached several times to the same DOM tree, you should avoid processing the same element multiple times. This can easily be done with jQuery Once.

(function($){
  Drupal.behaviors.myFunkyModule = {
    attach: function(context, settings) {
      // Get the map wrapper element (anywhere in the document).
      var map_wrapper = $('#map-wrapper');
      //Set the map-wrapper width and height to match the img size only once.
      map_wrapper.once('my-funky-module').css({
        width: $('#map-wrapper img').width(),
        height: $('#map-wrapper img').height()
      })
      // Get the (un-processed) .pin elements, in the context (ie. DOM tree) our behavior is attached to.
      var pins = $(".pin", context).once('my-funky-module');
      // Process the pin elements (note: this could also be done using jQuery.each()).
      for (i=0; i<pins.length; i++) {
           var pin = pins.eq(i);
          // store initial tooltips contents within an array
          var tooltipContent = new Array();
          tooltipContent[i] = pin.html();

          // set tooltip direction type - up or down
          var tooltipDirection = 'tooltip-up';
          if (pin.hasClass('pin-down')) {
              tooltipDirection = 'tooltip-down';
          }

          // Append the tooltip elements to the #map_wrapper one.
          map_wrapper.append("

" + tooltipContent[i] + "

");
      }

      // Add event listeners to show/hide the tooltip, again this only need to be done once.
      $('.tooltip-up, .tooltip-down').once('my-funky-module').mouseenter(function(){
        $(this).children('.tooltip').fadeIn(100);
      }).mouseleave(function(){
        $(this).children('.tooltip').fadeOut(100);
      });
    }
  }
})(jQuery);


Using Drupal Commons, how can I create a node of a specific content type on group creation? I am looking for a way to create a node of a specific content type at the same time as a group is created.

So basically, when a group is created a node of type my-content-type is created at the same time with og_group_ref pre-populated to associate it with the group just created...

I don't think there is a module for this, so... any pointers on to how to code this?

Here's the solution:

Obviously you need to download and install Rules, then:

Add an event:

After saving new content of type Group

2
. Add conditions:

Any conditions you want here..

3.Add Actions:

a) Create a new entity

Parameter: Entity type: Node, Content type: ContentTypeYouWantToCreate, Title: YourTitle, Author: TheAuthor
Provides variables: Created entity (entity_created)

b) Save entity

Parameter: Entity: [entity-created], Force saving immediately: true

c) Add entity to group

Parameter: Entity: [entity-created], Group: [node]

your content type should now be created when you create a new group - it will also be added to the newly created group.

Done!


D8 Programmatically change page orientation for Entity Print module In many projects, some entities needs to be printed on LANDSCAPE format, others, on PORTRAIT.
I was searching for an example or, maybe, a more precise way to implement a page orientation hook, but didn't really find any.
I just need to do something like

if($entity_type = "foo"){ set page orientation to portrait }

On this issue, benjy wrote :
If you need to do this programatically, see PrintEvents::CONFIGURATION_ALTER

I looked at the code and saw TestEngineConfigurationAlter class. So I tried to replicate this in a custom module, but it doesn't seem to do anything. I'm obviously missing a piece of the puzzle and I'm humbly asking for help.

Thank you very much :)

Related issues on drupal.org

2797877: Setting paper orientation for dompdf?
2715875: Setting paper size for dompdf in D8

Ok so here's a solution.

As mentionned, you only need to add an event in a custom module inside

my_module/src/EventSubscriber/EntityPrintSubscriber.php

I simply use a GET parameter from url to set page orientation.

ie. yoursite.com/print/pdf/entity_type/entity_id?orientation=portrait

namespace Drupal\my_module\EventSubscriber;

use Drupal\entity_print\Event\PrintEvents;
use Drupal\entity_print\Plugin\PrintEngineBase;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;

class EntityPrintSubscriber implements EventSubscriberInterface {

  public function alterConfiguration(GenericEvent $event) {
    //ie. /print/pdf/entity_type/entity_id?orientation=portrait
    $request = \Drupal::request()->query->get('orientation');
    if(!empty($request) && ($request == PrintEngineBase::PORTRAIT || $request == PrintEngineBase::LANDSCAPE)){
      $configuration = $event->getArgument('configuration');
      $configuration['orientation'] = $request;
      $event->setArgument('configuration', $configuration);
    }
  }

  public static function getSubscribedEvents() {
    return [
      PrintEvents::CONFIGURATION_ALTER => 'alterConfiguration',
    ];
  }

}

Edit:

Don't forget to add a service to your module.
So inside my_module/my_module.services.yml, add this:

my_module.entityprintconfig:
    class: Drupal\my_module\EventSubscriber\EntityPrintSubscriber
    tags:
      - { name: event_subscriber }


How to find unused or old twig template files? There are times when fields are deleted from a Content type, but there is no way of knowing if there is a related field twig template without manually looking in our repository.

Other than looking for file names, are there any utilities or other methods to find twig templates that are not being used?

It's difficult to find a deterministic method, so you probably need some kind of usage statistics.

A simple statistical method would be to clear the twig php cache:

\Drupal\Core\PhpStorage\PhpStorageFactory::get('twig')->deleteAll();

Then run the site for some time and check the twig php cache (/sites/default/files/php/twig) for twig files not having a compiled php template.


How can I detect whether the install process is running? I'm looking for a way to reliably detect whether Drupal's install process is currently running, either via drush site-install or install.php.

The immediate problem I'm trying to solve is that I have some settings (using Redis as cache backend) in settings.php which cause the installation to fail. So I'd like to wrap that block of settings in something like if (!drupal_installation_is_currently_running()) { … }

I have not managed to figure out how that can reliably be determined. Any suggestions?

You're probably looking for drupal_installation_attempted():

  Returns TRUE if a Drupal installation is currently being attempted.


How do I include tax and discount in computed field? I use the Commerce price by components module to display products' commerce_price field with tax and discount included.
It works as expected (I'm displaying the products' prices with a view in a panel)

I have another field, which is a Computed field, that I use to calculate the discount between the commerce_price field and a custom price field (MSRP).

Unfortunately, while the commerce_price is displayed with tax and discount included, the value sent to the computed field (from the commerce_price token) is the original value, without tax or discount applied, or any information related to the price components.

I can't figure out a clean way to apply the tax and the discount to the commerce_field value used for the calculation in the Computed field. How can I make the computed field receive the same token value as the one displayed?

I'm aware of the module Drupal Commerce Extra Price Formatters but using the Computed field gives me way more flexibility to calculate discount and special prices captions.

Surprising I did not find this function before, but this is what I needed:

commerce_product_calculate_sell_price($product, $precalc = FALSE)

Returns a price field data array as returned by entity_metadata_wrapper().


Creating a table with pagination in a Node Edit form I have a content type article that has a field for Category. In order to help our editors find related articles, I included a table on the article Edit page that pulls in other article entities that have the same category as the current one.

I did this by implementing a hook_form_alter hook and adding some markup to the $form object after querying for all related articles.

// Query for matching articles
$query = \Drupal::entityQuery('node');
$query->condition('type', 'article');
$query->condition('field_articles_category.entity:taxonomy_term.tid', $categoryId);
$query->sort('created', $sortDirection);
$query->range($offset, $limit);
$query->latestRevision();

/* Omitting logic to load the Node objects by revision ID's */
// $articles is an array of Node objects of type article

$articlesTable = []
foreach ($articles as $index => $article) {
   $articlesTable[$index] ['articleTitle'] = [
      '#type' => 'link', '#title' => $article->getTitle(), '#url' => $article->toUrl()
   ]
}

$form['related_articles'] = [
   '#type' => 'details',
   '#title' => 'Articles of the Same category',
   'articlesTable' => $articlesTable
];

The table displays just fine and shows the expected articles. But there are sometimes hundreds of articles in a particular category so I would like to paginate this table for performance reasons (and to make sure the page is not too long to scroll through). How can I paginate such a table?

I've seen some articles mention creating a pagination controller and somehow setting the AJAX callback for that controller, but haven't found a concrete example yet to follow.

You can use tableselect instead of details something like:

   $query = \Drupal::database()->select('node', 'n')
      ->condition('type', 'article', '=');
    $query->fields('n', ['nid']);
    $query->innerJoin('node__field_articles_category', 'category', 'category.field_articles_category_target_id = ' . $categoryId);
    //For the pagination we need to extend the pagerselectextender and
    //limit in the query
    $pager = $query->extend('Drupal\Core\Database\Query\PagerSelectExtender')
      ->limit($limit);
    $article_ids = $pager->execute()->fetchAll(\PDO::FETCH_OBJ);
    $rows = [];
    foreach ($article_ids as $index => $article_id) {
      $article = Node::load($article_id->nid);
      $rows[$index + 1] = [
        'title' => $article->getTitle(),
        'url'   => Drupal::l($article->getTitle(), $article->toUrl()),
      ];
    }

    $form['related_articles']['table'] = [
      '#type'    => 'tableselect',
      '#header'  => ['title' => t('title'), 'url' => t('Url')],
      '#options' => $rows,
      '#empty'   => t('No users found'),
    ];
    // Finally add the pager.
    $form['related_articles']['pager'] = array(
      '#type' => 'pager',
    );

Result will be like:


Question about template_preprocess functions i noticed there exists a template_preprocess_field function on the Drupal website, but i added in my template.php files just this...

function mytheme_preprocess_field(&$variables, $hook) {
   kpr($variables);
}

my question is, is the drupal function running too? in the system somewhere as well as my preprocess function?,

they seem to both be running. any insight would be helpful, thanks

Yes definitely it will go to parent function too because this is concept of overriding. But final impact would be of your override function.

Say example:

// Parent Function: First go to this fucntion

function template_preprocess_field(&$variables, $hook) {
   print "Parent Function";
   $variables['test_variable'] = "Parent data";
   ....
}

// Child Function: Override values using child function

function mytheme_preprocess_field(&$variables, $hook) {
   print "Child Function";
   $variables['test_variable'] = "Child data"; // Override value here
   ....
}

Now this $test_variable contains "Child data" value not "Parent data" because it is overrided.

I hope it would help you to understand basic concept of overriding.


Can I create a view that combines multiple images from single node with images from other nodes that entity reference the original node? I have a content type called "exhibition" that contains many images added via the standard image field. I also have a separate content type called "video" that uses an entity reference to point to an "exhibition". Each video node has a single image field for a thumbnail.

I want to create a block view that will be displayed on each exhibition's page in a sidebar that combines thumbnails of the exhibition's images with thumbnails of any videos linked to that node. How can I create this sort of combined view?

For example:
node/100 is an exhibition containing: image_1.png,image_2.png,image_3.png

node/200 is a video linked to node/100 containing: videothumb_1.png
node/201 is a video linked to node/100 containing: videothumb_2.png

I want a block to display in the sidebar of node/100 that renders the following:

image_1.png,image_2.png,image_3.png,videothumb_1.png,videothumb_2.png

I am experienced enough with Views that I can create a working block that displays image_1.png,image_2.png,image_3.png. I can also easily create a second block using relationships that correctly displays videothumb_1.png,videothumb_2.png. What I would like to do now is combine these separate block views into a single block. My attempts to combine the two seems to always lead to repeated images from the exhibition paired with repeated images from the videos.

if you can't get it to work any other way, you could try using Views Field View to combine the two:

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.


Add/List/Edit paragraphs while add/edit node I have installed paragraph module.

I have paragraph called Address contains relevant info.

It is attached to node.

Per page/article I have more than 100 address. If I use default Paragraph Classic view mode then page is going to be too huge.

What will be alternate solution?

Should be there List and Add button. Add/Edit/List will open in Modal Widget?

Need to use Entity browser and Paragraph Views.

I have been using the Paragraphs Collapsible module for a project with a big list of paragraphs to a node, and it works quite fine.

  Improves the Paragraphs widget by applying CSS tweaks and collapsible feature