Using theme_preprocess_node i'm trying to add a class to all images on the page My code below is not working and i'm not sure why. I've tried a few variants.
according to the KPR variables output, the image I'm trying to access is here.

$variables['field_about_image'][0]

i think the 0 signifies it is the first (and only in this case) image on the page w/ the machine field name 'field_about_image'. so i wrote my code as:

function myTheme_preprocess_node(&$variables){
    if($variables['type']=='basic_page_with_pic') {
echo '<script>alert("my func running")</script>'; //Verified it's working
    $variables['field_about_image'][0]['class'] = 'myclass;
}
}

i've also tried this, just to get a class attribute added

$variables['field_about_image'][0][] = 'class';

also the title attribute comes up as empty. so just as an execrcise i tried this.

$variables['field_about_image'][0]['title'] = 'some title;

any help on how to do this would be greatly appreciated!

From what I can tell, hook_preprocess_node() won't let you add both classes and title attributes to images from image fields. Try using hook_preprocess_field() as in the example below:

function myTheme_preprocess_field(&$variables) {
  if (($variables['element']['#field_name'] == 'field_about_image') && ($variables['element']['#bundle'] == 'basic_page_with_pic')) {
    $variables['items'][0]['#item']['title'] = t('This is the title text that will display when hovering.');
    $variables['items'][0]['#item']['attributes']['class'][] = 'class1';
    $variables['items'][0]['#item']['attributes']['class'][] = 'class2';
  }
}

Be sure to clear your cache.


Email Customer if Order Contains a Disabled Product I have Drupal Commerce configured on my site. Customers can purchase tickets to classes. However, if a class gets canceled, I need to notify any customers who purchased said class that the class is canceled.

I am thinking the best way to cancel a class is to set its status from "active" to "disabled". Once I do this, an email would be sent to any user who purchased said class.

I just don't know how to do this with Rules. Any help would be appreciated.

You can probably rig this up via Rules to automatically send the notification when the class is disabled, but I think it would be easier and probably better to separate out the disabling of the class and the notification of users. I'm not typically a fan of automatic side effects on entity updates - just imagine what would happen if that product somehow got re-enabled and you had to disable it a second time.

I'd create a line item View using Views Bulk Operations with an exposed filter that let me choose what product SKU to use to filter the results. You can do that either based on the line item's label value (since it initializes to the product SKU) or add a relationship to the referenced product if you've altered those labels somehow. You'll also want to add a relationship to the line item's order so you can filter it by orders in a certain status.

You can then use VBO to call a custom rules component that takes the line items from the View as arguments and then sends a notification out to everyone in the list. You may need to figure out either a Views query based method or a Rules variable based method to prevent sending the notification multiple times to the same user in the event that the account purchased the product more than once.


How to hide nodes in a VIEW where the user is not referenced? This is a follow-up to How to show nodes where the user is (not) in the reference field with Views?

I have a node with multiple user references and need a node VIEW that hides all nodes where the current user is NOT referenced. So, if the current user is not referenced, the node should not show up. The problem I just can't solve is that the node still shows up when other user are referenced (using exclude, it only excludes the current user from display, but it still displays the nodes for each other user that is referenced). I have unsuccessfully tried views_distinct module and VIEWs own "distinct" query settings.

If the user is referenced, the node should show up (this works from the above mentioned question)

CLARIFICATION:

Basically, it’s for a simple pay-per-view site. I need 1 (or 2, whatever works) VIEWS that shows the videos where the user has purchased access to (where he is referenced) and where the user has not purchased access to (where he is not referenced). After 48 hours the references are removed using rules scheduler.

Ideally in one VIEW, when the user is referenced, the link should be „watch“, where the user is not referenced, it should read „buy“ using VIEWS conditional and rules link. But two separate VIEWS are also ok.

Right now I have a content view (also tried it with a user view unsuccessfully, but this might be a saner approach?!). All of that works well with the notable exception of showing the nodes with multiple user references.

UPDATE:

Added a screenshot using the views argument substitutions.

UPDATE 2:

I tried it with regExpressions and views substitutions. The UID of the currently logged in user is passed as !1, but what is the correct regEx syntax to show only the nodes, where this user is not referenced?

This does not work as value of the operator on the useraccess field filter:

^***!1***

SOLUTION

Oh boy, this was a ride. Finally figured out a solution. Posting it if someone needs it. Basically, I added the username in the url and do a contains text comparison using views conditional. ID from the logged in user did not work as contains also shows user ID "13" or "14" when the user "1" is logged in. Simply excluding did not work in those cases where other users are referenced as well.

You have to add a filter under Filter Criteria Section which is, if a 'yourfield-name'is 'is not empty (NOT NULL)' from the select list.

This filter only shows results which have the value for this particular field. Otherwise it will not show you any result for that node.

I hope it will work.


How to overcome error caused by non-existent service "entity.manager"? I am running drush first time in my Drupal 9 project and getting the following error
 In CheckExceptionOnInvalidReferenceBehaviorPass.php line 86:
  The service "sanitize.userfields.commands" has a dependency on a non-existent service "entity.manager".

Is there anything I have missed?
I was trying to list all available commands.
After @hurdi's comment I found  drush --version drush cr are  working.
Note: It is my first Drupal setup and I'm learning it.

As folks (Hudri, leymannx) alluded to in the comments, entity.manager was deprecated in Drupal 8 which means it was removed in Drupal 9. The project that has the code that's calling entity.manager is not ready for Drupal 9 (or at least the version you have installed is not ready for Drupal 9). You may want to look for alternative modules if the one your using isn't ready for Drupal 9.
This one particular error is relatively simple to fix though, you may just need to replace any references to entity.manager with references to entity_type.manager. This issue on d.o gives a good example of what you may have to do.
As @Jaypan noted in the comments, entity_type.manager may not always be the correct replacement. From the entity.manager documentation:

Use \Drupal::entityTypeManager() [i.e. entity_type.manager] instead in most cases. If the needed method is not on \Drupal\Core\Entity\EntityTypeManagerInterface, see the deprecated \Drupal\Core\Entity\EntityManager to find the correct interface or service.

Note: if this issue is being caused by a contributed package, e.g. a d.o module or theme or other package included by composer, you need to work within that project's issue queue to patch the project instead of updating the files directly in your codebase. At the very least, you'll want to create a local patch in your composer project and configure composer to apply the patch.


How can I create another user login block? I would like the user login block to be standard on the front page, but a link on all other pages. The best way I can think of doing this is having two blocks and restrict them through the block setting.

Is there another way to do this? I have considered fancy login since that gives another login block, but I was curious if it's possible to clone the core login block. Thanks for reading.

You can't have the option assign a block to different region.But you can use the Multiblock

it will allowing you to create multiple Block Instances of already existing blocks.

If you want customize the login block with your own design, then this link will help you.


How do I 'programaticaly' create a new content type with hook_install in D7? I am trying to create a .INSTALL file which creates a content type (Apples) for my module (Fruit). I have dropped the following file (fruit.install) into my module folder with the .INFO file and .MODULE file. After enabling the Fruit module, I look into the database and find that there is no new entry in the node_type table. I must be missing a vital step? or I have made an obvious mistake, I think?

<?php

/**
 * Implements hook_install()
 */

function fruit_install() {

    // * If the content type does not exist then create it.
    if (!in_array('Apples', node_type_get_names())) {
        $type = array(
            'type' => 'apples',
            'name' => 'Apples',
            'base' => 'node_content',
            'custom' => 1,
            'modified' => 1,
            'locked' => 0,
        );
        $type = node_type_set_defaults($type);
        node_type_save($type);
        // * Set 'Apples' options
        variable_set('node_preview_apples', 0);     // Set 'Preview before submitting' to 'Disabled'
    }
}

The reason I was not seeing my 'Apples' content type appear in the node_type table was because I did not realise that I had to uninstall my module then reinstall it every time I wanted to test my code changes. I was just disabling the 'Fruit' module and expecting my .INSTALL file to do its work when I re-enabled the module again. You have to disable and uninstall (not just disable) then re-enable. Apparently you can manually remove the module from the system table also, but I did not go there.

The code I pasted in above does work - although it may not be the 'correct' way of creating a content type. I'm not sure. My method mirrors how I would acheive the same with the Field UI: Add a new content type, set the content type options, add any new fields, then create the required instances of those new fields. This seems logical to me, but you may find the other solutions suggested here to be better.


JS batch progress bar: possible to force refresh more frequently than every 1500 ms? After initiating a js-based batch with batch_set(), and the redirect to batch do URL, the JS refresh interval is every 1500 ms by default. So status message and progress bar are only updated every 1 1/2 seconds. For a specific application I need the refresh to happen more rapidly, let's say, every 500 ms. I couldn't find anything in batch_set() to set the refresh interval.

I believe that D8 core decides in file core/misc/ajax.es6.js that the default refresh interval ought to be 1500 ms, if nothing else specified:

if (this.progress.url) {
  progressBar.startMonitoring(
    this.progress.url,
    this.progress.interval || 1500,
  );

I could be wrong though and this code being only related to Ajax throbbers and such. The form Ajax API seems to have a way to pass #interval but I couldn't find anything for the batch API.

Be that as it may, my question is, how do I set my own custom refresh interval in a batch_set(), or if not there, is there another clean way to override the 1500 ms?

Thanks!

Turns out none of us (neither I or nor the commenters) were completely "right", nor completely "wrong". There IS an arbitrary limit hardcoded in D8's core, for JS batch progress bar refreshes, but it's not 1500 ms as I thought -- it's 1000 ms.

And it's harcoded in a different place than any of us thought.

As @MarioSteinitz stated, yes, the batch API inserts only a very short pause between two Ajax requests -- 10 ms. (The Ajax API is different with its 1500 ms default pause and I mixed up the two.)

However, try as I might, I couldn't get the progress bar to refresh more often than once every approximately 1.1 or 1.2 seconds. No matter how fast I finished my simulated batch work (by reducing my usleep() in the batch code), the relevant DOM objects, such as progress__bar, were never refreshing more frequently than just over once a second.

You can easily see their "throbbing" in Inspector's DOM view and count onethousand-one, onethousand-two as they pulse away... even when my batch function did absolutely nothing, the fastest I could get these DOMs to flash was just over once a second.

So what gives?

Well the batch API is just weiiiiirrrrrd... instead of giving the programmer the say in how much work ONE Ajax request is supposed to do, the function _batch_process() in core file /core/includes/batch.inc has a loop harcoded that calls the batch function again and again until at least 1000 ms have passed (or the batch is finished):

// If we are in progressive mode, break processing after 1 second.
if ($batch['progressive'] && Timer::read('batch_processing') > 1000) {
  // Record elapsed wall clock time.
  $current_set['elapsed'] = round((microtime(TRUE) - $current_set['start']) * 1000, 2);
  break;
}

Weird because a batch is ALREADY supposed to be a large process chopped into small bite-sized chunks. So the entire batch already IS a loop, but there's, in fact, a secondary inner loop, whose break conditions are outside of the coder's control!

You think this kind of policing of the programmer's wishes is not weird, arbitrary and unnecessary? Well consider that that the batch API (after what feels like decades), still doesn't allow progressive batches (i.e. batches that are all processed in one swoop, for example from the shell) -- see https://www.drupal.org/project/drupal/issues/638712.

But I digress.

So for sh*ts and giggles I changed the > 1000 to > 100 in the above core code and what do you know, the progress DOMs refreshed like crazy!

Of course I can empathize with the idea that no batch should hammer its host server with heavy requests every 10 ms, for obvious reasons. So the developers decided to loop and re-loop the batch function until at least 1000 ms have passed, before the next Ajax call is triggered.

Well-intentioned? Yes! Arbitrary and inflexible? Absolutely. As the programmer of a batch, I believe it should be MY choice how much exactly I want to do in one Ajax call. Any Drupal code has the potential to crash or deadlock the server, or overwhelm the browser. Why police this particular part?

Drupal maintainers: Why not default to 1000 ms if that is a trusty value for most applications or unaware coders, but for batches that require a more dense flow of output, let's say, once every 100 ms, give us the power to do that!

So how to get rid of the pesky > 1000 condition - without hacking the Drupal core of course!?

if ($batch['progressive'] && Timer::read('batch_processing') > 1000) {

If this were D7, we'd just manipulate the global $timers array: Just before our batch function exits, set its start value back to the stone age (01/01/1970), and the calling _batch_process() will always "think" at least one second has passed, and give control back to Ajax immediately.

Just that this isn't your grandma's Drupal; we are now all fancy object-oriented and stuff.

Looking at https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Utility%21Timer.php/8.2.x we notice that we can't just poke whatever we want into the Timer::$timers array any more. It is declared protected, i.e. no outsider, such as my batch function, is allowed to mess with its internal values.

So we're back to square one... or are we?

Well thankfully this is PHP and not a "real" programming language! (ducks)

Meaning, there's always a loophole to bypass any new-fangled OOP restrictions that those eggheads at Software Engineering University demanded. To hell with them!

After some googling, I wrote the following function. And by "wrote" I mean I all but stole it from people who know much more about PHP than I do: https://stackoverflow.com/questions/6448551/is-there-any-way-to-set-a-private-protected-static-property-using-reflection-cla

  /**
   * Revert Timer::$timers['batch_processing'] back to the stone age
   * to trick batch.inc / _batch_process() into thinking at least 1 second has passed
   */
  protected static function revertTime() {

    $obj         = new Timer();
    $refObject   = new ReflectionObject($obj);
    $refProperty = $refObject->getProperty('timers');
    $refProperty->setAccessible(true);
    $myTimers = $refProperty->getValue();
    $myTimers['batch_processing']['start'] = 0;
    $refProperty->setValue(null, $myTimers);

  }

I now call revertTime() at the very end of all my "batch on crack" functions, juuuuust before they exit. It sets the start time of _process_batch()'s Timer::$timers['batch_processing']['start'] to 0.

And 0 is always more than one second ago.

The effect is that _batch_process() never loops; the Ajax call terminates after exactly one call to my batch function.

10 ms later, the batch API initiates another Ajax call to my batch function, resulting potentially in a rat-tat-tat machine-gunning refresh cycle for my progress bar.

NOTE OF CAUTION: When I first ran this, with all checks and balances disabled, it overwhelmed Chrome with its rapid-fire Ajax calls every 10 ms. Today was a hot day (I live in the southern hemisphere) and my Mac slowed down to a crawl under the load of the Ajax calls... the built-in overheat protection kicked in!

When you use this hack, it is your responsibility to make your batch functions either do a LOT of slow stuff in one iteration, or waste sufficient time with usleep(). Otherwise the batch staccato may overwhelm your visitor's browser or your server.

Thanks again to all the contributors here and elsewhere who finally led me to a semi-clean (non-core hack) solution! ❤


Views and Panels Newbie... Maybe simple...Hope its simple I have a simple view that does not page. It contains about 50 records (three fields each). When I import the view into column one of the panel page, it displays the entire contents. I wish to equally divide the content into the two columns.

I have done this before in PHP. I have the code to do this in PHP. But this is D, so,...

I tried to mock up the effect, to get a look at the output, by placing the same view in the second column. But Panels apparently did not do another query. The second column was blank.

Any ideas why the view would not copy into the second column, or how I might achieve my goal to divide the query into two columns using Views and Panels the Drupal way?

I think you would not need panels for two column.

There are two ways I know:

Quick way: You can choose a styling format as grid and define columns as 2
Long way: A View listing can be shown in two columns by styling and template overriding.


Group audience versus group content visibility Can someone explain me what is the difference between group audience and group content visibility?

The basic concept is if you don't have any access control on the content specifically then the content would inherit the groups access control. But say you had a private group that you wanted some content visible (but not all) then the access control for the content could be set to allow that to happen.

You can read more in the docs here:
Content visibility:
https://www.drupal.org/node/2014755
Group visibility:
https://www.drupal.org/node/2014751

There are even some pretty diagrams listed in the content for more help visualizing these concepts.


image scroll on hover I'm not necessarily looking for a module for this, but I'm curious where to start to get the following functionality:

Each content entity has an unlimited amount of image fields. So if I had 5 images I want to be able to "scroll" through them on the frontpage. The scrolling functionality is that when you hover over the image, it shows different images. The frontpage is generated by a view

I'm basically making a TV show site with screenshots and I want the user to be able to preview some screenshots on the frontpage by simply hovering over the episode image.

It sounds like you want a slideshow for each content, based on that image field. There are many modules that offer that functionality, some themes, and you can always write or otherwise incorporate Javascript to handle it for you.


How do you add Meta-Description with Metatag? In the Node's options for Metatag, I have a token for the metatag "Description", i.e.: [node:summary].

If I want to write the description, should I delete it? Or write it in where the "summary" appears?

If you want to write a manual description you should delete the whole "[node:summary]" part and put your text in its place.

The square brackets are part of the token notation and aren't needed unless you are using replacement tokens.


How to replace login in "to" mail field? In registration notify email, or in emails sending by rules f.e., there is a prefix contained login of recipient in field "to". How can i change it for custom field value?
P.S. I use MimeMail module, if it matters.

I just had to fill 'to' field in a format 'custom name ', instead 'address@mail.com'.


What configuration is required to use date_views with a field? I have a custom entity "referral" which is available for views:

function mymodule_entity_info() {
  return array(
    'referral' => array(
      'label' => t('Referral'),
      'controller class' => 'EntityAPIController',
      'views controller class' => 'EntityDefaultViewsController',
      ...
    ),
  );
}

The mymodule_referral table has a field referred_at which is a timestamp (stored as an int); I'd like to add a filter on this field to my view. I've got it displaying and filtering correctly with hook_views_data_alter and views_handler_*_date, but I'd prefer popup date selectors.

I understand that the date_views submodule of date should do what I want, but I can't find proper documentation on how to use it.

function mymodule_views_data_alter(&$data) {
  ...
  $data['mymodule_referral']['referred_at']['filter'] = array(
    'real field' => 'referred_at',
    'handler' => 'date_views_filter_handler',
  );
}

doesn't seem to be sufficient, because it displays in the view edit page as

FILTER CRITERIA

    Referral: Referred_at (Missing date fields!) | Settings

If I open the settings there's a compulsory field

DATE FIELD(S) *
Select date field(s) to filter.

with no options to select.

The only reference I can find to the "Missing date fields!" error message talks about hook_date_api_fields, but that hook doesn't seem to exist in 7.

What configuration am I missing?

In addition to mapping 'handler' to 'date_views_filter_handler' you need to tell date_views that the field is a date:

function mymodule_views_data_alter(&$data) {
  ...
  $data['mymodule_referral']['referred_at']['filter'] = array(
    'handler' => 'date_views_filter_handler',
    'is date' => TRUE,
  );
}

In the filter settings for referred_at you will now see referred_at as an option for "DATE FIELD(S)", and if you select it then it will work as expected.


Folder permissions, owner/groups I am using the FileField Sources module

One of the features is that it allows you to transfer images from a URL to your drupal folder directly, instead of having to save the image on your computer and then selecting it for upload.

The problem I am having is that it won't let me transfer the file.

  http://anywebsite.com/picture.jpg could not be copied, because the
  destination directory is not properly configured. The folder
  permission is set to 775, as it should be.

I think it has something to do with the Owner/Group of Ubuntu.

In such cases, Drupal first downloads the image to the temporary directory and then moves it to the public directory. Go to admin/config/media/file-system. Make sure that both temporary and public directories are defined and both are writeable by the web server. The easiest way to do this is to make the web server user the owner of the directory. The command is:

sudo chown -R www-data <directory>

where www-data is the web server user. Depending on your OS and web server, the user could be apache2 or httpd as well.


Is there any way to show a progress bar during loop iteration in a rules? I have made a rule set and in my rules I load a collection of nodes into a list and by iterating, I perform some modifications in each node.

Sometimes the number of nodes is more than 500.

I want to know is there any solution in order to show a progress bar during loop processing ?(such as one when we update a module)

I found the solution.

At first I must appreciate Eyal who gave me key point .

I used module named "rules_batch" in https://www.drupal.org/project/rules_batch and it solved my problem.


field widget with multiple input fields I need to create a custom field widget that is actually a 2 input fields group. I also need to save these values (I guess this is done through hook_field_schema())

The main problem is that I'm a little bit confused about how to use hook_field_widget_info() and hook_field_widget_form() and how are these connected with the hook_field_schema()

Any insights / links about this? Thanks

As well as their schema and other basic definitions, fields have

Widgets

  Field API widgets specify how fields are displayed in edit forms. Fields of a given field type may be edited using more than one widget. In this case, the Field UI module allows the site builder to choose which widget to use. Widget types are defined by implementing hook_field_widget_info().

Formatters

  Field API formatters specify how fields are displayed when the entity to which the field is attached is displayed. Fields of a given field type may be displayed using more than one formatter. In this case, the Field UI module allows the site builder to choose which formatter to use. Field formatters are defined by implementing hook_field_formatter_info().

Each field needs a widget and formatter to do anything useful, but they don't necessarily have to be implemented by the same module that implements the field. For example, you could piggyback off of one of the select widgets if that made sense for your field.

For full code examples, check out the Examples module


security report there is no .htaccess file in private:// directory I have this security report  that is constantly saying:

  Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your private:// directory which contains the following lines:

Deny from all

#Turn off all options we don't need.
Options None
Options +FollowSymLinks

#Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006

<Files *>
  #Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

I have this exact file in sites/all/default/files/private. what could be wrong?
The private folder has the permissions set to 644.

When you say sites/all/default/files/private I presume you mean sites/default/files/private.

I suggest deleting sites/default/files/private/.htaccess and setting the permissions of sites/default/files/private to 777 temporarily. Drupal should then be able to recreate the .htaccess file which should be exactly correct.

There are other reasons this can happen, I just can't remember off the top of my head sorry. I've had this same problem before.


DB Query exclude duplicates, returning only the newest I need to alter the query below to only return one row for each unique 'name'. The row returned should be the most recent based on the contents of 'date'. 'date' is an integer.

$query = db_select('updates_summary', 'n')
->fields('n', array('upid', 'name', 'date','previous_version','new_version'))
->orderBy('date', 'DESC') //Most recently updated first.
->execute();
return $query;

I have looked at the Drupal page on Expressions, another Drupal answers question and questions on drupal.org like this and this. Unfortunately I am new to the db-api and am struggling to get anywhere.

This works to return a single date but nothing else in the other columns:

  $query = db_query("SELECT MAX(upid) as max_id FROM updates_summary")->fetchCol();
  return $query;
}

NEW ADDITIONS:

This is the mySQL query I need an equivalent of:

SELECT `name`, MAX(date) FROM `updates_summary` GROUP BY `name`

Adding ->groupBy('name') to my query seems to do what I need it to. However, i am confused as to why this seems to be working without specifying that I want to return the maxium from the date column. My current code that seems to work is:

  $query = db_select('updates_summary', 'n')
->fields('n', array('upid', 'name', 'date','previous_version','new_version'))
->groupBy('name')
->execute();

return $query;

I would like to add a MAX(date) as I did in the mySQL statement above. This answer suggests that adding the following should work: ->addExpression('MAX(date)', 'max_date') but i get Fatal error: Call to a member function fields() on a non-object.

You can use range() to limit your results

$query = db_select('updates_summary', 'n')
->fields('n', array('upid', 'name', 'date','previous_version','new_version'))
->orderBy('date', 'DESC')->range(0,1);
$query = $query->execute();
return $query;


Problem updating node module from drupal 6 to drupal 7 I am trying to update my drupal version from 6 to 7. I have a problem, I use the next link http://localhost/drupal6/update.php and when the process said "Updating node module" it never finish.

I use WAMPSERVER in WINDOWS 8.1

The problem seems to be with the Locale module. I would suggest disabling the Locale module in D6, running the D7 update.php, then enabling Locale and running update.php again.


How to configure or style an Openlayers source? I'm just getting started with Drupal Openlayers. I've created a simple map consisting of one views geojson view. What I want to know is how to customize the display of the layer, such as the type of marker for the points, etc. I'm just not sure where these setting are.

Any advice would be appreciated.

You won't find any options in Views to customize the display.
Have a look under "admin/structure/openlayers".
Markers are defined under "styles" -> admin/structure/openlayers/styles.


Modify field names in REST export I want to use a custom field in my Views REST export, but rather than having "nothing": "My custom text", I would like "mycustomtext": "My custom text". Is there a way to do this from within the UI?

Serializer settings: force using field & json

Show: fields

Show settings: type an alias for each field

Above settings are shown in the images below


Add custom access check to user page I would like to add an additional access condition to viewing user pages like user/1.
I looked at the following guidelines, but have not succeeded in coming up with a solution.
https://www.drupal.org/docs/drupal-apis/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones
and
https://www.drupal.org/docs/8/api/routing-system/access-checking-on-routes#access-custom
The module code I have come up with this far - I can restrict all access to user profiles fine.
But I fail at my attempt to get the account id of the page being requested. Once I have the account I can load the field I need to check.
my_module.services.yml
services:
  my_module.route_subscriber:
    class: Drupal\my_module\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

my_module/src/Routing/RouteSubscriber.php
<?php

namespace Drupal\my_module\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 *
 * We deny access to profiles, if the user has not accepted the terms.
 *
 * See https://www.drupal.org/node/2187643
 *
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    $path = \Drupal::service('path.current')->getPath();
    $path_args = explode('/', $path);
    // @todo: the right path does not seem to be accessible here - how do we get the user account id?
    // Always deny access to '/user/{uid}'.
    // Note that the second parameter of setRequirement() is a string.
    if ($route = $collection->get('entity.user.canonical')) {

      //$account = \Drupal\user\Entity\User::load($account_uid);
      // This effectively denies all access to user profiles
      $route->setRequirement('_access', 'FALSE');
    }
  }

}

EDIT:
Based on the comments I tried the following, but I am not being restricted to paths like /user/1, so I guess something is still amiss:
My module structure now looks like this:
/my_module
  /src
    /Access
      my_moduleAccessCheck.php
    /Controller
      my_moduleController.php
    my_module.info.yml
    my_module.routing.yml
    my_module.services.yml

my_moduleAccessCheck.php:
<?php

namespace Drupal\my_module\Access;

use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;

/**
 * Checks access for displaying configuration translation page.
 */
class my_moduleAccessCheck implements AccessInterface {

  /**
   * A custom access check.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(AccountInterface $account) {
    // Check permissions and combine that with any custom access checking needed. Pass forward
    // parameters from the route and/or request as needed.
    // $account->hasPermission('do example things') && $this->someOtherCustomCondition()
    return AccessResult::forbidden();
  }

}

my_moduleController.php:
<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * An example controller.
 */
class my_moduleController extends ControllerBase {

  public function sayHi() {
    dpm('Hi');
  }

}

my_module.routing.yml
my_module:
  path: '/user/{uid}'
  defaults:
    _controller: '\Drupal\my_module\Controller\my_moduleController::sayHi'
    _title: ''
  requirements:
    _my_module_access_check: 'TRUE'

my_module.services.yml
services:
  my_module.access_checker:
    class: Drupal\my_module\Access\my_moduleAccessCheck
    arguments: ['@current_user']
    tags:
      - # Required: Mark that this service is for access checks.
        name: access_check,
        # Optional: Specify which routes this applies to.
        applies_to: _my_module_access_check

I ended up using hook_ENTITY_TYPE_access():
use \Drupal\Core\Entity\EntityInterface;
use \Drupal\Core\Session\AccountInterface;
use \Drupal\Core\Access\AccessResult;
use \Drupal\Core\Access\AccessResultInterface;
/**
 *
 * Implements hook_ENTITY_TYPE_access().
 */
function my_module_user_access(EntityInterface $entity, $operation, AccountInterface $account) {

  // Deny access to user profile for other members if the user hasn't accepted the terms
  if (!$entity->id() === $account->id()
      || !$entity->hasField('field_profile_visibility')
      || $entity->get('field_profile_visibility')->value === NULL) {
    \Drupal::messenger()->addWarning(t('The profile is not visible because this user has not accepted the terms of this site yet.'));
    return AccessResult::forbidden();
  }
  return AccessResult::neutral();
}


Display the Group Title after the content in Views Grouped By I've got a View which displays a grid of content. The nodes are of type Photo Gallery and I'm showing a grid of thumbnails, each thumbnail representing one node. I'm grouping the content by Post Date so it appears like this:

There are two galleries posted on 09/04/2013, 1 gallery on 09/01 and 3 galleries on 08/28 and this is all well and good. However, my client would like the group title to appear below the content. So it should show Rome 2 and Rome 2013 and then below that should show Post date: 09/04/2013.

Is there any way I can make the group title render after the content instead of before?

You should override the views-view-grid.tpl.php for your views. Otherwise, it will be effect all grid layout into your site.

The correct template suggestions for views be views-view-grid--[views_name].tpl.php or views-view-grid--[views_name]--[display_id].tpl.php.

To know more template suggestions for views, you can follow below step.

Go to Administration » Structure » Views
Edit your views
Open the correct display of the views.
Click on  information link for theme under Advanced tab.
A popup be display for all template suggestions for a particular
views.


Drupal Commerce - Add to Cart form tweaks I am setting up a very simple drupal commerce site for a few courses with 3 product variations for different price levels. I created a product type "Course Registration" and gave it these payment options:
DEP|Deposit
EB|Early Bird
FULL|Full Price

I have a content type "Course Display". On the bottom of a product display page I get this:

Payment Option
o Deposit
o Early Bird
o Full Price
[Add to Cart]
$250

From what I've been able to figure out the radio buttons and submit button are displayed part of the "Add to Cart form" widget for 'product' field. The price is coming from the 'Product: Price" field. I would like have the price show above the submit button like this:

Payment Option
o Deposit
o Early Bird
o Full Price
$250
[Add to Cart]

I assume this means getting the "Add to Card form" to show the price? I'm at a loss for how to proceed.

Thanks!

You can add the rendered field into the add to cart form like this:

function mytheme_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {
  $product = $form_state['default_product'];
  $view_mode = $form_state['context']['view_mode'];
  $form['price'] = field_view_field('commerce_product', $product, 'commerce_price', $view_mode);
}


How to hide/show menu items using based on group membership? I want to hide and/or enable certain menu links that are present on my main navigation bar depending whether users are/aren't part of any group.

I am currently using the Rules module with these settings but these delete and recreate the links completely! I just want to hide them from the view.

I have used the "update menu item" as action.

A better way of doing this might be to use Drupal's built user permissions. You can use a 3rd party module such as https://www.drupal.org/project/content_access so set specific access

E.g. so that only certain roles have access to those certain pages. Then drupal will automatically handle the showing/hiding of the menu links if they depending if the user does/doesn't have access to that page


Will removing the X-Drupal-Cache header break anything? I have a client that wants to get rid of as much server information as possible from their headers, including "X-Drupal-Cache".

I know that anyone technical enough to be looking at headers can very likely tell that Drupal in plenty of other ways  but that's beside the point.

It is easy to remove the header but if I do will it potentially break anything?

Note: I'm aware that there is a similar question at X-Drupal-Cache http header but that issue has long ago had an accepted answer that does not cover my specific question.

X- headers are optional, and are not allowed to be officially required, except in the same family of products. You can search Internet for some bizarre examples. My favourite is X-PoweredBy: Unicorns and X-hacker: If you’re reading this, you should visit ******.com/jobs and apply to join the fun, mention this header.

That said, it may not be required, but it may still be used. If your hosting company provides caching and load balancing, it may use this header to know that page came from Drupal's cache and thus there is no need to use that data to repopulate cache server's storage. It can be also used to track statistics. and of course you are using it to test if cache works OK on production, aren't you? All these uses will get impossible if you will remove this header, or rename it without coordination with other users. Site should be served OK, but in specific circumstances there is a risk of worse performance and crippled debug/analytic options. Maybe you can afford that risk. Maybe not.

TL;DR You need to ask anyone who might be using it, not us.


What is going wrong with the file_field_path redirect for my files? I am using the fieldfield_path module to create a redirect for my files as they come in during a migration (this is so that I can give an original path in the migration, and create a redirect, allowing me to redirect at the apache level from the old url to a new one, but also have extra information in the path that wasn't available from the old site path.  The fieldfield path file path is set to publication_documents/pub/[node:field_doc_type_book]/[node:nid] for my book content type public files field.

When I look at my migration messages I see the following message:

Creating redirect from
private://publication_documents/pub/old/1565/filename.pdf to
private://publication_documents/pub/book/37544/filename.pdf

Which is what I would expect, the nodeid of the node the file is attached to is 37544.  Unfortunately when I actually visit /system/files/publication_documents/pub/old/1565/filename.pdf I get redirected to system/files/publication_documents/pub/book/149678/filename.pdf

Which is a page not found error page.  It is a mystery where the number 149678 came from, but I can confirm that the redirect happening is the one actually stored in the redirect table.  I've looked through all of the node and revision ids, file ids, etc. that I could think of as possibly being the source of this mystery integer, but have had no luck so far.  I removed all the migrated data and ran the migration again, but the integer on the redirect is still the same.

What might be happening?  Why is drupal telling me it is creating one redirect, but actually creating another?  I suspect it is actually creating the one it is telling me about, but then replacing it with another, but so far, I don't have any information to prove either theory.

I am using the media module, and wonder if that is somehow messing things up.  I also have pathauto active.

It turned out that what was happening is that the old redirects were never being deleted when I rolled back my migrations.  When I did a reimport, the source for the redirect already existed so new ones weren't being created.  To solve this I implemented hook_node_delete as follows (I need to delete redirects to system/files/publication_documents/{either int or pub}/{the value of a field}/{node id}) :

function MYMODULE_node_delete($node){
    // Delete alias.
    $nid = $node->nid;

    $type = $node->{'field_doc_type_' . $node->type}[LANGUAGE_NONE][0]['value'];
    foreach (array('pub', 'int') as $status) {
        redirect_delete_by_path('system/files/publication_documents/' . $status . '/' . $type . '/' . $nid);
    }
}

This works when the redirects have been created with the current $nid, but this wasn't true for any of the existing redirects in the system, so I wrote remove_redirects.php:

<?php
redirect_delete_by_path('system');

and then I rolled back my entire migration and ran drush scr remove_redirects

This cleared out the existing redirects, so I can run the migration again, and future rollbacks will get rid of the redirects too.


How to display all nodes by user on his profile page I want to create a view of "users" /profiles/<RealName> which lists selected fields from user content type. I accomplished this. But now, I want the same view to display selected fieds from the nodes created by this user.

I tried to do it by myself, but I'm unable to add relation to desired content type.

PS: I'm a newbie so kindly throw some details in your answer.

1.Create a view for content of type all 2.Inside the view display node title and all other fields as per your requirement. 3.Add a contextual filter content : author uid 4.While adding that you will have a option for provide a default value 5. select that option and inside that use filter by 'currently logged in user'. 6. Save it by this you will be able to see all the nodes of current logged in user. 7. Inside the path you can enter just any path like '/my-nodes'. and you are done.
8.If you want you can avoid providing default value and switch to manual input
by placing the path as '/my-nodes/%' and then just add contextual filter as 'content : author:uid' without default value(depends as per the requirement).
9.For user name you can add a relationship content author:uid then
 in the contextual filter use User name with relationship author:uid


How to debug a delete query? I'm trying to debug an issue with a delete query not happening. I've added logging before the query, after the query and I'm logging the return value of the query. Everything looks right, the only problem is that the rows are still in the database.

It's a simple query, I can't see anything wrong with it:

$result = db_delete('cloud_files')
  ->condition('uri', $uri)
  ->execute();

I've checked the $uri in every way I possibly can and it's right. I've tried executing the delete query by hand and it works just fine. The table name is correct, the field name is correct, the $uri is correct. I don't know what else to check.

I've used the Devel module to log the queries and while it logs queries that happen both before and after this query, it doesn't log this query at all. However, I've got error_log() calls before and after the query so I know this code is being run and it reports that it is running successfully.

I've even added code to select the data before deleting it and it works!

$select = db_select('cloud_files', 'cf')
                ->fields('cf')
                ->condition('uri', $uri)
                ->execute();

$entry = $select->fetchAssoc();

error_log("entry: ".print_r($entry, true));

That works, it prints out the row I'm trying to delete.

dqp() doesn't work for delete queries, so I don't know of any way of getting the truly final sql being executed.

I've made sure that if I connect using the mysql command line client from the drupal host with the user/password in the drupal config that all of the commands work.

How do I debug this? What is going wrong?

EDIT:

Is there any kind of transaction happening during a delete action? Could this behavior be the result of those delete queries happening in a transaction that gets aborted?

With a problem like this, you may need to turn on MySQL query logging.  Once logging is enabled, put a noticeable query right before and after your DELETE query (do you can have something easy to search for), check the logs, and go from there.  Just be sure to disable logging when you are done.  It can kill performance and also fill up the disk pretty quickly.


How to empty the cart automatically before adding a new item to the cart? How to empty the cart automatically before adding a new item to the cart in ubercart ver 6?

Is it possible adding uc_cart_empty($cart_id) ; in uc_cart module?

You can clear the cart using the following function

uc_cart_empty(uc_cart_get_id());

Use the above function in your module when you want clear cart.
To empty the cart automatically before adding a new item to the cart call the function in hook_add_to_cart().

eg:

function MODULE_NAME__add_to_cart($nid, $qty, $data) {
  uc_cart_empty(uc_cart_get_id());
  drupal_set_message("Previous item cleared");
}


views block display based on url I have a view with exposed filters which only returns results when a filter is applied and it all works fine. I also have a block underneath the view which I only want to show before a filter is applied. I have set the block only to display on a url for example

  /view

which is the path of my view, when you apply filters the url path becomes

  /view?var=arg

at this point I don't want to display the block

Turn on php filter module shipped in core, so to get option to add php codes option to set block visibility at the block configuration.

Remember you have to make sure, php code should be appropriate else it will not allow to access the site till you delete the added php codes from database for the block.

Code which might help you

<?php
  if ($_GET['q'] == 'view' && count($_GET) == 1) {
    return TRUE;  // block will be shown
  }
  return FALSE;
?>


Displaying Organic Group members based on a Views Contextual Filter The end goal here is to get a list of organic group members based on a contextual filter.

The path for the view is groups/%/members, where the contextual filter is "OG membership: Group ID" and defaulted to custom PHP code. (Because the "Current OG from Context" wouldn't work.)

The custom PHP code is as follows (based off of this solution on d.o):

 if(arg(0) == 'groups' && arg(1) != null){
  $node_path = drupal_get_normal_path('groups/'.arg(1));

  $node_id = substr($node_path, 5);

  // Check if node referenced by arg(1) is a group
  if(og_is_group('node', $node_id)){
    return $node_id;
  }
  else {
    return null;
  }
}
else{
  return null;
}

There is a relationship to OG membership: OG membership from User there also. It makes no difference if the contextual filter is referencing the relationship or not.

If I "Preview with contextual filters" in the Views UI with a group's NID, the view works. So I know it's just the default value of the contextual filter.

I have something very similar in the "No Results Found" section for troubleshooting purposes, the only differences is it outputs some additional strings to clarifiy where the returns are firing. When I save the view and go look at the page, it returns "No results found" but also returns the correct NID/GID from the PHP. My suspicion is that the PHP code isn't validating with views for some reason.

The view needs to be a page, so I can't use the default block view provided by the OG module. ("OG members (user)")

The only thing I am set on is a working solution, so if you have a suggestion on doing it differently, I am open to other ideas.

Contextual filters I have tried that do not work are:
-Content ID from URL
-OG Group from context
-Raw value from URL

Any help or point in the right direction would be greatly appreciated.

Thanks!

Okay so the problem turned out I was returning the wrong variable.

I needed to return $handler->argument instead of whatever variable I was using.

So my function I put in my contextual filter was:

if(arg(0) == 'groups' && arg(1) != null){
  $node_path = drupal_get_normal_path('groups/'.arg(1));

  $node_id = substr($node_path, 5);

  // Check if node referenced by arg(1) is a group
  if(og_is_group('node', $node_id)){
   // return $node_id;
   $handler->argument = $node_id;
   $node = node_load($node_id);
   $handler->validated_title = $node->title;
   return $handler->argument;
  }
  else {
    return null;
  }
}
else{
  return null;
}

(I cleaned up the code a little and adjusted it to strip out the unnecessary stuff.)


Is it possible to move product category description alignment in drupal Can any one suggest me to move Product description from top to bottom in drupal product category page.

Example Like :

First all product Image.
And Bottom content are shown.

This can be also done through the admin dashboard. Follow the below steps:

Go to admin/structure/types.
Select your content/Product type and manage Display according to your requirement.


How to replace the $title of one single page with a taxonomy term? My setting here is like this:

I have a huge Druapl site here, and there's one single page that contains a views block displaying uploaded files with their taxonomy terms in a table. Title of this page is "Uploaded files".

Clicking on of these taxonomy terms calls the URL plus an additional query ?tid=123 applying a filter for that term on the table. So now only content of taxonomy tid 123 is displayed in the table and the URL ends with ?tid=123.

In that situation I want the title "Uploaded files" to be replaced by "Files of the taxonomy term 123", where 123 stands for the actual term connected to the tid 123. Let it be "To-Do-List".

Inside my theme's template folder I created a template file for that single page called page--node--nid.tpl.php, where nid stands for the actual node id of that page. I'm quite well able to manipulate the title of that page now when clicked on a term. At the place where the title is printed I can say <?php print $_GET['tid'] ?> and of course instead of "Uploaded files" it now prints the tid, here in my example: 123.

But how do I get the template to print the term instead of the id?

I know that there's a function called taxonomy_term_load to load the term connected with an id. But where would I call that function? And how do I pass maybe newly created $taxonomy_title into my page--node--nid.tp.php? Do I have to call some preprocess functions within the  tags at the top of my page--node--nid.tpl.php?

To make matters even more difficult, there are terms from different vocabularies. In my example it sets the query to ?tid=123, but when I click on a term from another vocabulary it sets the query to ?tid_1=234

I came so far on my own, but do really very much appreciate a helping explanation on how and where to use that function...

You can achievie that with contextual filters as well.

contextual filter: Content: Has taxonomy term ID

When the filter value is NOT available:

provide default value -> type: Taxonomy term ID from URL
Load default filter from node page, that's good for related taxonomy
blocks
check the vocabulary which you want to use

When the filter value IS available or a default is provided:

Specify validation criteria -> PHP Code

$term = taxonomy_term_load($argument);
drupal_set_title($term->name);
return $argument;

It's done!


Get other users data custom value how can I get all (custom) data from other users ?

With my admin account, I want to show them in a page.

For example :

  user 1 :

  name
  age
  custValue

  custValue1 / 2  / 3

I want to get custValue and the other data (custValue is the most important)

Example of values that I want to show :

Drupal 8 :

$user = \Drupal\user\Entity\User::load($uid);
$value = $user->field_name->value;

For multiple values, use

$value = $user->get('field_name')->getValue();


Download image without watermark I have a content type that includes an image field. After the image is uploaded, I add a watermark to this field using the Imagecache Actions module.

I would like to allow users to download the image without watermark. Is it possible?

Before watermarking the image, store the original copy in another, private file mode image field.

Then you can control access to the original image with hook_file_download().


Pager missing in View I have a view with navigation set to paged, 12 items. I can see 12 items (there are way more available), but no pager. Googling this problem I found the following solutions that didn't work:

View uses Global: PHP fields (my view doesn't do that)

View is displayed in a block (my view is displayed in a page)

Changing pager id (tried everything from 0 to 5, also, this is the only pager on this page)

It's also not a styling issue, the pager is not in the markup. I didn't override any templates related to the view.

In other views, the pager works and I can also see it in the views preview. In this view, I can't even see it in the preview - this should prove that it's not a theming issue as well, am I right?

I tried displaying a "more" link, but that didn't work as well. Changing the navigation to "mini pager" also doesn't help.

The view is using a relationship to an entity reference, but that shouldn't be an issue IMO. Other than that it's a pretty ordinary view displaying some fields. Anyone have any ideas?

(Drupal 7, Views 3)

I'm guessing you have caching enabled for this view.  You can disable caching for this view or, better, you can apply this patch: https://www.drupal.org/node/1819538


How to delete events from Full Calendar? I'm using FullCalendar module

I have added an event. Now I want to delete it. How can I remove/delete an event from the calendar?

if you want to be able to delete nodes directly from the calendar, here is how:

make sure you have the tokens module installed/enabled.

in your fullcalendar view, add the Content:Nid field.
add a global:custom text field that is under the nid field you just added, and input the following as the text:

node/[nid]/delete
click on the fullcalendar settings (under the format heading) and click "customize fields" click the "use a custom redirect URL" checkbox, then in the dropdown, select your custom text field you created in step 2.
save the view.

now when you click on the event, it will ask you to confirm or cancel the deletion of the node.


Changing the module path on custom install profile I would like to have the profile install the modules I list in my profile .make to sites/all/modules/contrib instead of in the profile directory profiles/my_sweet_profile/modules/contrib is there any way to do this without having to use a script to copy the modules, and then rebuilding the drupal registry?

I have read this DA post, but the answers contained pertain to the more canonized distribution profiles (OpenAtrium). I am not going to be rerunning this installation profile on the same site, so there is no need for me to preserve the initial structure.

Thanks!

You can get an example in Videola profile:
https://github.com/Videola/videola/blob/master/videola_starter.make - main make file which downloads only profile from github.

Then see main make file with all the modules: https://github.com/Videola/videola/blob/master/videola.make which shows you an example of what you want to do.

projects[admin][subdir] = "contrib"


Bootstrap Views Grid Unable to specify Medium and Small device classes I am currently using https://www.drupal.org/project/views_bootstrap and successfully created a Bootstrap Grid

For each grid item I get the following output as the root most div tag

But I need to add more class names as follows

is there a facility to provide additional classes which needs to be added in the root component of each rendered view content?

I had a similar issue some months ago. It seems Bootstrap Views allows this possibility, but only in the dev release, not in the latest stable release.

In order to do what I wanted in the stable release of the module, I ended up with the following solution:

/**
 * Implements preprocess_views_view__VIEW().
 */
function scicnet_preprocess_views_view__MY_VIEW(&$vars) {
  $display_id = $vars['display_id'];
  switch ($display_id) {
    case 'MY_DISPLAY':
      $vars['rows'] = str_replace('col-lg-4', 'col-lg-4 col-md-4 col-sm-12', $vars['rows']);
      break;
  }
}

Not the most elegant solution, I admit, but it does the job...


efficient way to apply content permissions My site has content type "Department News". There are 10 departments, each one should have permission to create and edit its own "Department News", everybody can view everything.

How to implement it?

My idea is to create 10 roles - one for each department - and the only difference between them will be Create and Edit access to a specific content type.

Then create 10 identical content types, just named differently - and configure permission for the Department-Content matrix.

The question: is it possible to implement it somehow more efficiently, at least without creating 10 content types which are identical, only for the purpose of assigning permissions to them. Best would be also to get rid of the 10 roles and e.g. check additional permission for "Department News" based on a field in user profile.

Duplicating almost identical roles and content types is a burden from maintenance point of view.

Have you tried looking into Organic Groups?  It seems like the PERFECT solution to your problem.  It'll require a bit of work to set up, but the benefits will FAR outweigh the work.

You could have each department set up as a group, and then users can be assigned to those groups.  You can then set permissions that allow users to create content but only for their specific group (using OG means that this can be ONE content type).

You'd only need one user role (an organic groups user..you could also have a department admin per department should you want).

You can also do some more awesome stuff from here on out.  Just as an example, these departments could then view their own department content - but you can also display all posts from all groups.

There are some REALLY good videos at Modules Unraveled


A module for migrating data from an SQL file only into a new site? I have an SQL file of my Drupal 7 site. I want to migrate data only from it's SQL file (and afterwards all it's images manually) to a fresh, minimally-installed Drupal site that already has all the needed modules for the update.

Is there a module that could load all the SQL data --- All the nodes\views\image paths\Redirects from the SQL directly?

Thanks!

No, that makes no sense. Import it into a database and migrate it from there.


Creating multiple custom blocks in drupal 8 ├── hello_world
│   ├── hello_world.info.yml
│   ├── hello_world.module
│   ├── hello_world.routing.yml
│   └── src
│        ├── Controller
│        │   └── HelloController.php
│        └── Plugin
│             └── Block
│                  └── HelloA.php
│                  └── HelloB.php

I have used the above file structure to create blocks in Drupal 8. Both the blocks, HelloA as well as HelloB works, but only one at a time. I see block HelloA, if I remove HelloB.php and see Block HelloB when HelloA.php   is deleted. I am trying to create multiple blocks. Please guide me. Thank you very much.

Thank you very much Shawn.

It was the @Block annotation. I was using same id for both the blocks.

/**
  * @Block(
  *   id = "show_state",
  *   admin_label = @Translation("Show State"),
  *   category = @Translation("POP")
  * )
  */


|slice filter does not work with special characters I try to use the slice filter in order to limit a link to a specific amount of characters. The field that I render is a link field and my code is the following:

{% set title_text = title|render|striptags %}
<span>
     {{ title_text|length > 65 ?
         title_text|slice(0,65)  :
         title_text|striptags}}
</span>

Unforturnately some characters like the apostrophe are not rendered appropriately.

So instead of rendering "I've learned", they render "I& #039;ve learned"

Actually the culprit is |striptags

  The problem with using twig's |striptags is double encoding of html entities,
  not markup, so & becomes & and then &amp; – Berdir

  source: How do I get the raw field value in a twig template?

If your setup relies on you running striptags last, you will need to do this all of this magic in a preprocess function with php setting a variable here and then printing your formatted variable on twig.


Can I temporarily stop update notifications for one project only? Is there a way I can tell Drupal not to notify me about a particular version of a module? For example, if it isn't security related and I choose not to update one module but would like to receive notifications about other modules (or future versions of the module in question)?

The Drush command from one of the answers to this question is close to what I want except if there are future security updates I would still like to know about it, just no more notifications for this particular version.

drush pm-updatecode --lock=module_to_ignore

See Update Advanced module:

  Extends the administrative interface for Drupal core's "Update status"
  module. In particular, the per-project settings to ignore certain
  projects or even specific releases, is absent in the core version of
  the module. The "Update status advanced settings" module restores
  these settings, and might eventually provide additional functionality
  for the core "Update status" module.


How to get uid from a node on which is commented? I'm using hook_comment_view($comment) and I'd like to confer the uid from the comment ($comment->uid) with the uid from the node on which is commented. I thought of $node->uid, but I don't know how I can define $node.

Any suggestions?

I could load the $nid via the comment and confer the uid's like this:

function mymodule_comment_view($comment) {
 $nid = $comment->nid;
 $node = node_load($nid);
 if ($comment->uid == $node->uid){
    //do something
 }
}


Views Ajax error with jquery 1.8 I'm using Bxslider which required jquery 1.8 to be responsive. However, when using jquery 1.8 I get errors with views when trying assign and change values.

How should I solve this problem?

Installing the 7.x-2.x-dev version of jquery allowed me to select version 1.5 of jquery for administrative pages and solves my problems.


How To Upload Image From Media Library Programmatically? I enabled latest version of media module to upload images in wysiwyg. It is working fine. There is no problem. I want to upload images programmatically from media library.
  Below is my code.

function test_form_upload_form_alter(&$form, $form_state) {
 $form['settings']['apply_now_image'] = array(
  '#type' => 'media',
  '#title' => 'Image for apply now',
 );
 $form['#submit'][] = 'test_upload_form_submit';
}

function test_upload_form_submit(&$form, $form_state) {
    global $user;
    if (!empty($form_state['values']['apply_now_image'])) {
    $file = file_load($form_state['values']['apply_now_image']);
    // Change status to permanent.
    $file->status = FILE_STATUS_PERMANENT;
    // Save.
    file_save($file);
    file_usage_add($file, 'user', 'user', $user->uid);
    $apply_now_image_path = file_create_url($file->uri);
    variable_set('rgit_apply_now_image', $apply_now_image_path);
    variable_set('rgit_apply_now_image1', $file->fid);
  }
}

But it didn't give correct answer. This is only work if the '#type' is managed_file'. It didn't work if the '#type' is media. Is any solutions there to upload images from media library.

Not sure what you are trying to achieve here, but files uploaded via media are already permanent managed files once you get to the submit stage, I believe.

The value in the form_state array you need is $fid = $form_state['values']['apply_now_image']['fid']);

You can then use that in a file_load: $file = file_load($fid);

So your code becomes

$file = file_load($form_state['values']['apply_now_image']['fid']);
file_usage_add($file, 'user', 'user', $user->uid);
$apply_now_image_path = file_create_url($file->uri);
variable_set('rgit_apply_now_image', $apply_now_image_path);
variable_set('rgit_apply_now_image1', $file->fid);


How to email individual content to email field? I have a content type that contains information about people, if these people want this information forwarded to them, I'd like to be able to capture an email in an email field and send the published content to them in an email.

I've been hunting around for a way to do this but can't find anything. Is there a way to do this?

If you're looking for existing module to base a solution on. The Print module has a Send by email submodule that supplies a form (/printmail/node/NID) that you can tweak for sending out emails and capturing the supplied emails.

/**
 * Implements hook_form_print_mail_form_alter().
 */
function MYMODULE_form_print_mail_form_alter(&$form, &$form_state, $form_id) {
  // Add a custom submission handler for your functionality.
  $form['#submit'][] = 'MYMODULE_form_print_mail_form_submit';
}

function MYMODULE_form_print_mail_form_submit($form, &$form_state) {
  // @TODO: process $form_state['values']['txt_to']['addrs'] for email addresses to store.
  // Use $form_state['values']['path'] to the load relevant node & save data to its fields.
}


How to add an additional class to each element in the menu-local-task.html.twig template? I need to change the admin tab template by adding my wrapper and class to it.
This is the default code:

{{ link }}

My code:

{{ link }}

Currently, the "DefTabs__tabItem--active" class is added to the active link, but I need to add an additional CSS class "DefTabs__tabItem" to each DIV element. How can I do this?

Create an array, ex:
{%
    set classes = [
      is_active ? 'is-active',
      'my-second-class-name',
    ]
%}

{{ link }}

Currently, the "DefTabs__tabItem--active" class is added to the active
link, but I need to add an additional CSS class "DefTabs__tabItem" to
each DIV element.

By the way, no need to repeat yourself with the naming, do this:
{%
    set classes = [
      'DefTabs__tabItem',
      is_active ? 'active',
    ]
%}

{{ link }}

Then in CSS you can target the active with .DefTabs__tabItem.active { ... }


Image gallery with mobile view optimization I'm using Drupal 7, and I want to have a photo gallery.

When viewing the gallery using mobile phone or ipad, I wish to have the photos shown like facebook photo gallery:

image will auto resize according to screen size
when user slides the image to left or right, it will shows previous or next photo

Is there any module which can achieve the above effect?

You may try out the Photoswipe module (dev).


How to progragrammatically get NodeType translated value in D8? Fetching node translation

$node = Node::load($nid);
$node->getTitle(); // returns title in en(default language).
$translated_node = \Drupal::service('entity.repository')->getTranslationFromContext($node, 'es');
$translated_node->getTitle(); // Returns translated title in es (spanish).

If we want to fetch the bundle's translation. The above approach doesn't work.

Kindly advise?

$article = $node->bundle();
$article->label(); // returns "Article".
$translated = \Drupal::service('entity.repository')->getTranslationFromContext($article, 'es');
$translated->label(); // Also returns "Article".

Translation for bundles provided from /admin/structure/types/manage/article/translate/es/edit

You need to set the config override language to the desired language:

  $language = $language_manager->getLanguage('es');
  $original_language = $language_manager->getConfigOverrideLanguage();
  $language_manager->setConfigOverrideLanguage($language);

  // Load the node type here.

  $language_manager->setConfigOverrideLanguage($original_language);

Taken from user_mail()


Why does include() call PublicStream::stream_set_option()? I am including a PHP file that in stored in the public:// directory.
(Yes, I know that's generally a bad thing, but there are reasons, and this is done on a local development server.)
I get this warning.

User warning: stream_set_option() not supported for local file based stream wrappers in Drupal\Core\StreamWrapper\LocalStream->stream_set_option() (line 356 of core/lib/Drupal/Core/StreamWrapper/LocalStream.php).

I don't understand what's going on.
Why is include() calling PublicStream::stream_set_option()?

It happens with PHP 7.4, where one of the backward incompatible changes is the following one.

When using include/require on a stream, streamWrapper::stream_set_option() will be invoked with the STREAM_OPTION_READ_BUFFER option. Custom stream wrapper implementations may need to implement the streamWrapper::stream_set_option() method to avoid a warning (always returning FALSE is a sufficient implementation).

Even with the latest code committed in Drupal 9, LocalStream::stream_set_option() triggers the user error you are seeing.
public function stream_set_option($option, $arg1, $arg2) {
  trigger_error('stream_set_option() not supported for local file based stream wrappers', E_USER_WARNING);
  return FALSE;
}


strtotime() doesn't return unix timestamp in custom view when $row->field_date is an English date I'm confused. I'm using a Global: PHP field inside a view to tweak the output of the row based on the date value of a certain field.

print (strtotime((string)$row->field_date));

Doesn't seem to return anything.

print $row->field_date;

Returns "Tuesday, December 1, 2015"

print strtotime('Tuesday, December 1, 2015');

Returns 1448956800

I've tried converting the $row object to an array just for fun with get_object_vars($row) but that didn't work either.

In my case I expect that print (strtotime((string)$row->field_date)); returns the value (unix timestamp) 1448956800.

$row->field_date contains markup, not just the date/string value hence strtotime() won't/can't return a valid unix timestamp. To fix, try using strip_tags() around the returned value of $row->field_date like:

strtotime(strip_tags((string)$row->field_date));

or use "Strip HTML tags" option checkbox under "Rewrite Results" in the "Configure field" dialog.


How can I set variables only once per block? I have a block module that displays some data taken from XML. That module has multiple  (approx. 7) blocks, each of which displays a different "view" of the same XML. Each block can be positioned independently on the page, but all of the blocks are displayed at once and all of the blocks use the same data.

Since the XML parsing code runs inside the block_view() hook, it runs once for every block.

My problem is that the XML parsing is expensive in terms of time (not hugely so, but easily >95% of the total module runtime), and this is a page that I want to run as fast as possible.

How can I move the XML parsing out of the block_view() hook and run it once per page view? Is there another hook that will let me set some global variables or something like that?

function my_module_block_info() {
    $blocks[0]['info'] = t("My Module: block one");
    $blocks[1]['info'] = t("My Module: block two");
    $blocks[2]['info'] = t("My Module: block three");
    ...etc (~7 blocks total)...
    return $blocks;
}

function my_module_block_view($delta = '') {
    $parsed_stuff = parse_some_xml();
    switch ($delta) {
        case 0:
            $block['subject'] = t('Blah');
            $block['content'] = block_0_html($parsed_stuff);
            break;
        case 1:
            $block['subject'] = t('Yada');
            $block['content'] = block_1_html($parsed_stuff);
            break;
        case 2:
            $block['subject'] = t('Etc');
            $block['content'] = block_2_html($parsed_stuff);
            break;
        ...etc (~7 blocks total)...
    }
    return $block;
}

You can use static caching in your parse_some_xml function. Some people consider this a cleaner, less evil solution than using global variables (but I will not get into that discussion here).

With static caching, your my_module_block_view() would remain the same, but your parse_some_xml() would look like this:

function parse_some_xml() {
  static $parsed_xml;
  if (!isset($parsed_xml)) {
    // Do the actual parsing here, and store the data in $parsed_xml
  }
  return $parsed_xml;
}

See A Beginners Guide to Caching Data to learn more about static caching.


Theme the User Edit Profile page I am using the Edit Profile module.

This module takes all the fields attached to a user profile and displays them on a separate tab located at yoursite.com/user/[USERID]/edit-profile.

I would like to theme the fields on this edit profile page. How can I do it?

I have tried two approaches but none seem to work:

Approach 1: Tpl.php suggestion from theme developer

Theme Developer suggests to use the following template: page--user--edit-profile.tpl.php
This however has two problems:
1) It affects the whole page and not just the user profile form.
2) It doesn't seem possible to access the fields on the user profile from this template.

Approach 2: template.php

The form ID of the user profile edit form is edit-profile-user-profile-form so I used the following code in my template.php file to override it:

function THENAME_theme(&$existing, $type, $theme, $path) {

    return array(
        'edit-profile-user-profile-form' => array(
            'arguments' => array('form' => NULL),
            'template' => 'templates/edit/user-profile',
            'render element' => 'form',
            ),
    );

}

This, however, only over rides the main user profile page and not the fields on the edit tab. Can anyone help?

I have figured this out.

The solution is to use approach 2 (in my opening post). However, in the template.php file, you have to remove all the dashes from the form ID (edit-profile-user-profile-form) and replace them with underscores.

So the code in template.php would be as follows:

function THENAME_theme(&$existing, $type, $theme, $path) {

    return array(
        'edit_profile_user_profile_form' => array(
            'arguments' => array('form' => NULL),
            'template' => 'templates/edit/user-profile',
            'render element' => 'form',
            ),
    );

}

Next create a file called user-profile.tpl.php and save it in templates/edit.

In the user-profile.tpl.php file, use the following code to print out the fields:

<?php print drupal_render($form['field_NAME_OF_FIELD']); ?>


Converting from a WordPress theme I'm converting a WordPress theme. And, yes, I'm following the very good advice listed in a previous question. My question is more granular. So hence, this new question.

Specifically, I'd like to address the menu creation. Should I use the typical theme() functions to build out Main and Secondary menus? What class names should I pass into that theme function?

Currently, I've cleaned up the HTML template by extracting all embedded JS and CSS into external files. It appears as

                home

about

Drop Down 1

Drop Down 2

Drop Down 3

books

movies

time travel

blue box

boats

Or, can I loop over a render variable to produce the
, leaving the
 and
's in place? Does this deviate too far from best practice?

Well, here is the code that I've put in place. So far it's respecting the CSS selector patterns that the WordPress theme rendered.

       <?php
       print theme('links__system_main_menu', array(
         'links' => $main_menu,
         'attributes' => array(
           'id' => 'nav',
           'class' => array('menu')),
         'heading' => t(''))
       );
       ?>


Add static text on flag confirmation form? The flag confirmation page works fine with standard fields, but I would like to add a basic description/help text/guidelines text field that is admin-controlled and doesn't show up on the flag form as an editable field per each flagging.

Basically:
Are you sure you want to flag x?
{Flagging Guidelines} <- add
Fields from manage fields show here

flag confirm / cancel

It can be done in the hook_form_alter. You can just add markup element to this form with flagging guidelines


Behaviour attach triggering twice At some point in an update in the last few months, Drupal (7) started routinely triggering attached behaviours twice.

At first I thought "this is my fault, my behaviours should check to see if they've been run in this context already", and I set about using jQuery's once() (and other such solutions).

However I'm convinced now that this is a wider problem. e.g. the admin_menu module generates 2 admin menus.

Has anyone found this and the cause of it and a solution (beyond patching every module in use to check for duplicate calls)? I'm not sure where to start looking!

Nb. I've said "drupal" is doing this, I suppose it could be a contrib module that's causing the behaviour. I've seen it across several sites (I manage a dozen or so)

I put a breakpoint on one script's attach behaviours and inspected the call stack both times it was called.

The first time was expected, from drupal.js, and the second turned out to be from a call in the EU Cookie Compliance module. This turned out to be a bug in the EU Cookie Compliance module.

Thanks for comments. I'll leave this here in case anyone else of the 70.5k users of that module experience the same issue!


How to add pagination after using hook_views_post_execute() to modify $view->result? I have successfully used hook_views_post_execute() to remove results I do not want from $views->result.

Now, however, I need to paginate the remaining results.

The code in my hook_views_post_execute() requires the full result set to work. If I edit the view in the admin interface and set it to 10 items per page with full pagination, the $views->result in hook_views_post_execute() will only include 10 items, so my code doesn't function properly.

It looks like I need to use hook_views_pre_render() to set up the pagination, but I'm not sure how.

Can someone point me in the right direction?

I eventually realized that hook_views_query_alter() was the appropriate hook, but it wasn't working because this view utilizes Search API. Turns out hook_search_api_views_query_alter() is a hook specifically for altering the query when using Search API.

I used this hook to add a condition to the view query before it is executed. This allowed me to turn pagination back on in the admin panel and have it work as anticipated.

function mymodule_search_api_views_query_alter(view &$view, SearchApiViewsQuery &$query) {
  if ($view->name === 'my_view_name') {
    // Do some stuff to get the nids I'd like to allow in my result set.
    $nids = array(1, 2, 3, 4, 5);

    // Add the condition to the existing query.
    $view->query->condition('nid', $nids, 'IN');
  }
}


Download file from field instead of going to node page What I'm trying to achieve is: create a new content of type arquivo, then when accessing the new content url, instead of showing a page with the fields and etc., the file from a field_file is opened/downloaded. Tried to achieve this using a custom template for the content type with no success.
The code for the tpl.php is:

<?php
$items = field_get_items('node', $node, 'field_arquivo');
$filepath = $items[1]['uri'];
$path = file_create_url($filepath);
drupal_goto($path);
?>

Any help is appreciated

You could make a custom module and put this function in it

/**
 * Implements hook_node_view().
 */
function custom_tweaks_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'arquivo' && $view_mode == 'full') {
    $file = $node->field_file[$langcode][0]['uri'];
    if ($file) {
      $file_uri = file_create_url($file);
      drupal_goto($file_uri);
    }
  }
}


Get Post data of a view in inside a block I am actualy tring to get the posted data from a views filter and display it inside a custom block.

This is what my code looks like for now

<?php
/**
 * Implements hook_block_info().
 */
function search_block_header_block_info(){
    $block['search_header'] = array(
        'info' => t('Search Header'),
        'cache' => DRUPAL_NO_CACHE,
    );
    return $block;
}

/**
 * Define what our block is going to look like.
 * Implements hook_block_view().
 */
function search_block_header_block_view($block_key){
    $block = array();

    if($block_key == 'search_header'){ //We only want to define the content of OUR block

        dsm($_POST);
        //This is the title of the block.
        $block['subject'] = t('Search Header');
    }

    return $block;
}

But for some reason the $_POST variable is always empty. Someone got a hint for me how to get the posted data?

Try

$view = views_get_current_view();
dsm($view->exposed_input);

instead $_POST.


How to create node twig template suggestions for one content type? I need to create a node twig template that is just for the basic page content type that based on a custom field on the content type. We have other content type like Article, Blog, Products that do not need these specific twig template.

How would we create twig templates based on the field_type so that it only applies to the basic page content type?

Here is what we tried, but couldn't find how we could detect for the basic page content type and the value for the field_type. We tried ksm($suggestions) and ksm($variables), but it does not print which implies that the hook isn't called even after clearing cache.

function mymodule_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  // This is what we are looking for.
  $node_bundle = $node->bundle();
  if($node_bundle == 'page') {
    // we want something like this.
    $node_type_value = $node->field_type->value;
    $node_view_mode = $node->view_mode; // not sure what this would be.
    $suggestions[] = 'node__' . $node_bundle . '__' . $node_type_value
  }
}

You need to get the values first you want to work with. For example the node object is inside $variables['elements']['#node']. In the sample below field_foobar is a text field. Depending on what your field type is you may need to get the value you want a little bit differently. And also maybe sanitize it first before you use it in a template suggestion (replace spaces etc.).

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  /** @var \Drupal\node\Entity\Node $node */
  $node = $variables['elements']['#node'];
  if ($node->bundle() === 'page') {
    if (!$node->get('field_foobar')->isEmpty()) {
      $value = $node->get('field_foobar')->first()->getValue()['value'];
      $view_mode = $variables['elements']['#view_mode'];
      $suggestions[] = 'node__page__' . $view_mode . '__' . $value;
    }
  }
}


Different path for multilingual view With the Drupal 7 module Internationalization Views it was possible to add in a view a different url-path in each active language.

In D8 i found only a solution with a redirect, but i'ts the way i want it.

Any suggestions?

I think you are searching for URL alias for different language.

Go to /admin/config/search/path/add where you can add alias for different language.


Add new existing field for existing content type I have a development site (let be site 1) and a site where I check my code (site 2). My goal was to add a new existing field to a paragraphs type (/admin/structure/paragraphs_type), so I did the following:

On site 1:

I re-used an existing field in one of the paragraphs type
I exported the configuration
I deleted uuid and _core.default_config_hash from the configuration files (from those which was relevant for me)
I wrote an update hook which will create the same config file (except order), when my module will be updated on other sites, where it was previously installed my module
I put the exported 3 files to my module's config/optional dir

Than I moved this module to the site 2 where I run the update hooks. But the newly added field wasn't showed up on the paragraphs type's page under the correct paragraphs type. All the configuration's dependencies are right and enabled. Configuration file is same except the order. If I want to add the field on site 2 manually again, after config import I get this error: There was a problem creating field : 'field_config' entity with ID 'paragraph.text_boxes.field_text' already exists.

Note: before I added the new field, I had a configuration export under git, so after I added a new field and exported the configuration I saw exactly which configs was touched.

What am I doing wrong? How can I add a new existing field to a paragraphs (or a content type)? What's missing?

if I am not wrong, I believe, Site 1 is your local development environment, and site 2 is your production environment.

I wrote an update hook which will create the same config file (except order), when my module will be updated on other sites, where it was previously installed my module
Why would you write an update hook ? You can simply export the configs, and import them on prod.
If this does not suit you, I would suggest you to use Features module for this. It will make sure you get a working module which can be installed even without features module in place on Prod.


Structuring groupcontent with taxonomy I have a site with three grouptypes (organic groups).
I am still sort of finding out the right structure as i want each group type to have
their own (predefined) taxonomyterms. (og vocab will not work as this is per group)

Should i give each grouptype a different groupcontenttype. This way i can divide my vocabularies over each groupcontentype. This way i will have a clear distinction per grouptype. However it results in more maintenance as i need to make views (filtering taxonomy) and panelpages per grouptype.

Is there some other way that i am not aware of using just one groupcontenttype for all my grouptypes and being able to set the proper vocabulary on them?

If the number of group types is relatively small and consistent, you might consider adding several taxonomy term fields to the base groupcontenttype, each referencing the relevant grouptype specific vocabulary, and then hiding the fields that are not relevant to a group's type.

If you hid the field on the node edit page using a switch statement (on group type) in hook_form_alter, then ensured that empty fields were not displayed on the node, then both visitor and admin would not see irrelevant fields.


Views Bootstrap (Carousel) Not Working I've installed the Views Bootstrap module primarily so that I can easily create the same carousels that the Bootstrap/non Drupal parts of our site use. I would prefer to use Views Bootstrap or else I will have to use a different carousel module and try to style it so it looks the same.

I have for images in my result set. All I am getting right now is a page with one number for each image like this:

1.
2.
3.
4.

Below this I get the images, left aligned, one per row.

In the view settings I am using Bootstrap Carousel for Format and Bootstrap Carousel for Show. I get this same result whether I am using this view as a block or as a page. I don't know if it matters but I am using the Omega 3 theme.

Any help would be appreciated.

Thanks

To use Views Bootstrap module you need to have theme that based on Twitter Bootstrap. If your theme is not based on it, you may take a look to similar modules, such as Nivo slider


How to include exposed filter name in views data feed export CSV title? Trying to get views data export to save file with selected token from exposed filter

In the settings I can see this explanation:

%exposed == effective exposed filters, like filter1_foo-filter2_bar

So I tried this:

%[field_industry_type].csv
%field_industry_type.csv
%field_industry_type_tid.csv

But can't get nothing to work, what I'm trying to do is use a field filter as .csv name, one of the filter types is industry, so if industry is "relocation" I would like the file to save like this:

relocation.csv

Maybe my token syntax is wrong?

%exposed itself combination of the number of exposed filters you have on your view. When you save file name only with %exposed.csv it should generate file name as per your request would be like "industry_relocation.csv".

So, %exposed will generate based on "FIELDIDENTIFIERNAME_VALUE-ANOTHERFIELD_VALUE".

To generate a custom file name you should use hook_views_pre_build() function. You can find examples here: https://www.drupal.org/project/views_data_export/issues/1288612


how to add field programmatically in Drupal 7 with dynamic content value? I have a function in my e-commerce website that allow users to create own stores, i need to add dynamic field (select list) contain the stores created by the logged user when he add new product to assign this product with store.

i try to add field on the content type 'product' but i found that drupal save the values in the database.
What is he best method that resolve my problem?

I'm not sure what you are trying to do. But if you are trying to add a new field programmatically, below is a code snippet that can get you started.

    $myField_name = "my_new_field_name";
    if(!field_info_field($myField_name)) // check if the field already exists.
    {
        $field = array(
            'field_name'    => $myField_name,
            'type'          => 'image',
        );
        field_create_field($field);

        $field_instance = array(
            'field_name'    => $myField_name,
            'entity_type'   => 'node',
            'bundle'        => 'CONTENT_TYPE_NAME',
            'label'         => t('Select an image'),
            'description'   => t(''),
            'widget'        => array(
                'type'      => 'image_image',
                'weight'    => 10,
            ),
            'formatter'     => array(
                'label'     => t('label'),
                'format'    => 'image'
            ),
            'settings'      => array(
                'file_directory'        => 'photos', // save inside "public://photos"
                'max_filesize'          => '4M',
                'preview_image_style'   => 'thumbnail',
                'title_field'           => TRUE,
                'alt_field'             => FALSE,
            )
        );
        field_create_instance($field_instance);
        drupal_set_message("Field created successfully!");
    }

Hope that works

Muhammad.


Get the last revision id of any given entity? Is there a single, unified method in Drupal 7 to get the last revision id for any given entity object?  If so, what is that method?

I think entity_extract_ids() is the quickest you'll get:

  Helper function to extract id, vid, and bundle name from an entity.

e.g.

list($nid, $vid, $bundle) = entity_extract_ids('node', $some_node);


Where is the the site name and slogan set? In the page--front.tpl.php template, I have the following code for site logo.

<img src="<?php print $logo ?>" alt="example.com logo" title="<?php print $site_name_and_slogan ?>" id="logo" />

Where is the title set in Drupal 7? Right now the title is showing blank in the production site.

In your active theme's template.php, check template_preprocess_page() function and add following lines:

$site_name = variable_get('site_name');
$site_slogan = variable_get('site_slogan');
$variables['site_name_and_slogan'] = $site_name . ' ' . $site_slogan;

Assuming that you have used $variables as argument in template_preprocess_page() function.

Now $site_name_and_slogan can be used in page tpl files.

If you have not implemented template_preprocess_page() function, then replace template word with your theme name and add the function as mentioned below:

function THEMENAME_preprocess_page(&$variables){
  $site_name = variable_get('site_name');
  $site_slogan = variable_get('site_slogan');
  $variables['site_name_and_slogan'] = $site_name . ' ' . $site_slogan;
}


How to display result of a View in a specific block? I have a View displaying the content of a Custom Content Entity.
The first output I created is a Page display (accessible with a path and an option in a menu).
As expected, this is displayed in the 'Content' region of the default theme (see capture below).
I'd like to output the result in a full width region of the theme, i.e. without the content of 'Sidebar First' (User account menu, Search).
I duplicated the Page Display as a Block Display and placed it. But, of course, it appears on every page of the site :-(
So I created a single basic page (node/xx) and I configured the block to show only in this page. But I had to hide 'User account menu' and 'Search' on this page too.
Is there a more simple way to achieve this?

You are going about this the wrong way. Start again with a page display for your view.

Now you want to remove the sidebar from that page. Two ways you might do that:

Disable all blocks in the sidebar when the path matches the one for your view. You'll need to configure each one separately with the path criteria.
Override the page template with one that does not have the sidebar code. The template will be named something like page--my-path.html.twig (See https://www.drupal.org/docs/8/theming/twig/twig-template-naming-conventions).

There are other approaches but these are probably the simplest to implement.


In Drupal 7, how do you git clone a module project quickly? There doesnt seem to be any good documentation on a quick way to git clone a module project. I have already read this: https://drupal.org/project/examples/git-instructions

The following format does not work for me:

  git clone --branch 7.x-1.x http://git.drupal.org/project/examples.git

I am getting this error:

Is there a way to do a git clone quickly by copying a url without having to put in --branch 7.x-1.x versions... or better yet is there a drush command to do a git clone? All i want to do right now is do a git clone of a project and provide a patch to the maintainer, but im hitting resistance setting this up.

Just use the format you say doesn't work. This is the correct format. The URL does matter. (Do not use the format that produces the error.)

I.e. to clone branch 7.x-1.x of tb_megamenu, you should use:

git clone --branch 7.x-1.x http://git.drupal.org/project/tb_megamenu.git

You may skip the --branch option and branch identifier when cloning.  This will clone the current HEAD, which may (or may not) be the head of the branch you want.


Comment permission settings Please kindly help if you know a solution for this or a ready module you may be aware of:

1:I need to set a node a way that each user can only see their own comment and replies to that.
2:Also I need for some nodes, a user can see other users comments, only when he/she has a comment on that node already.
3: A group can see only each other comments on a node.

I hope this can be done by a setting when we are creating a node.

Thanks in advance for any help.

AFAIK there are no modules that provide the functionality of 1), 2) & 3) out of the box.

There is an awesome module Comment Permissions that can help you achieve better customization of comment permissions than Drupal core provides. You can take it as an example and expand the functionality that it already has to suit your needs.

  The Comment Permissions module enables control of commenting by user
  role and by node type. Additional user permissions for selected node
  types are added to the user access system so you can configure
  commenting with more control than Drupal core provides.

Permissions provided by module (accessible via Permissions page & can be configured for each content type):

administer comment settings on any page content
administer comment settings on own page content
comment on any page content
comment without approval on any page content
comment without approval on own page content
edit own comments on page content

Hope this helps.