How do I migrate content to a field added with UI to an existing custom content entity? In a custom module (assoc), I have a custom Content Entity (Person) with these fields:

$fields['lastname'] = BaseFieldDefinition::create('string')
$fields['firstname'] = BaseFieldDefinition::create('string')
$fields['email'] = BaseFieldDefinition::create('email')
$fields['cellphone'] = BaseFieldDefinition::create('telephone')

I migrated Person content from a Drupal 6 site using Migrate Source CSV, Migrate Plus, Migrate Tools and this migration file:

id: migration_persons
migration_tags: null
migration_group: null
label: 'Person migration from CSV'
source:
  plugin: csv
  path: /Users/efalzon/Sites/JdP8M7b/config/migration_Persons.csv
  delimiter: ';'
  enclosure: '"'
  header_row_count: 1
  keys:
    - id
process:
  id: id
  lastname: lastname
  firstname: firstname
  cellphone: cellphone
  email: mail
  iscontact: iscontact
  isactive: isactive
  member_id: member_id
  user_id: user_id
  owner_id:
    plugin: default_value
    default_value: 1
destination:
  plugin: 'entity:person'
migration_dependencies:
  required: {}
  optional: {}

I added a field to this entity using the UI:

The corresponding config files are field.storage.person.field_sel_initial_credit.yml and field.field.person.person.field_sel_initial_credit.yml
I tried to migrate some content to this field using

id: migration_sel_initial_credit
migration_tags: null
migration_group: null
label: 'Sel initial credit migration from CSV'
source:
  plugin: csv
  path: /Users/efalzon/Sites/JdP8M7b/config/migration_Sel_initial_credit.csv
  delimiter: ';'
  enclosure: '"'
  header_row_count: 1
  keys:
    - uid
process:
  bundle: "person"
  entity_id: uid
  revision_id: uid
  field_sel_initial_credit_value: value
destination:
  plugin: 'entity:field_storage_config'
migration_dependencies:
  required: {}
  optional: {}

and I got this error when executing the migration:

[error]  Attempt to create a field storage without a field name. (/Users/efalzon/Sites/JdP8M7b/web/core/modules/field/src/Entity/FieldStorageConfig.php:252)

What am i missing?

In fact, it was easier than I thought. I just had to add the field to the Person migration file:

id: migration_persons_with_sel
migration_tags: null
migration_group: null
label: 'Person migration from CSV'
source:
  plugin: csv
  path: /Users/efalzon/Sites/JdP8M7b/config/migration_Persons.csv
  delimiter: ;
  enclosure: '"'
  header_row_count: 1
  keys:
    - id
process:
  id: id
  lastname: lastname
  firstname: firstname
  cellphone: cellphone
  email: mail
  iscontact: iscontact
  isactive: isactive
  member_id: member_id
  user_id: user_id
  field_sel_initial_credit: credit <----------
  owner_id:
    plugin: default_value
    default_value: 1
destination:
  plugin: 'entity:person'
migration_dependencies:
  required: {  }
  optional: {  }


How do you update a user role to be an admin role via Drush sql-query? I know the following User ID 2524 and the Name is Tester. And the role to be an admin is 3. What command is needed to make a user an admin using only the the drush terminal?

I do not see a reason to execute a sql query, when this can be as simple as

drush user-add-role "administrator" --uid=2524

To see more options with command type

drush help user-add-role


Jquery in ajaxed loaded content referencing incorrect node id I have a list of nodes each with a click. The click sends a node reference argument which loads a new view using ajax. Jquery collects the node reference number via a hidden input value on the content-type-tpl.php. Likewise the nodes in the new view each have a click which sends a node reference argument which loads a new view using ajax. However while the clicks in the original view work correctly, the clicks in the newly called view do not reference the correct node. Instead of referencing the node id for the node which is clicked, the node id of the next node in the view is collected instead. Oddly when placing <?php echo $node->nid;?> on the content-type-tpl.php, the correct node id is echoed on the page. But sadly this is not the one sent to the view argument. So clicking any node in the the newly loaded ajaxed view, sends the id for the next node. Here's the javacript:

 Drupal.behaviors.ajaxlinks = function (context) {
    $('.morelink:not(.togg-processed)', context).addClass('togg-processed').each(function () {
      var myindex = $('.morelink').index($(this));
      var target = $('.newthing').eq($('.morelink').index($(this)))
      var nid = $(".mynid").eq(myindex).val();
    $(this).click(function() {
if (($('.hiddenrows').eq(myindex).is(":hidden"))
|| ($('.shownrows').eq(myindex).is(":visible")))
{
    $('.hiddenrows').eq(myindex).show();
    $('.newthing').eq(myindex).show();
      var toLoad = Drupal.settings.basePath + 'replies/' + nid;
      xhr = $.ajax({
        url: toLoad,
        success: function(data) {
        $(target).css( "height","200px" );
        $(target).html($(data));
     Drupal.attachBehaviors(context);
}
});
}
else
{
    $('.hiddenrows').eq(myindex).hide();
    $('.newthing').eq(myindex).hide();
}
    return false;

It's the same code so I can't see why it works differently in the newly loaded view. Can anyone spot what I am doing wrong?

Looks like Drupal.attachBehaviors should have fired on (target) instead of (context). It was refiring the script on the whole context instead of just the new ajaxed content. So I changed Drupal.attachBehaviors(context); to Drupal.attachBehaviors(target);

Now it works!


Drupal 8 Permission to see Structure > Menu Drupal 8. I want a user with a certain role to be able to see and administer menu items /admin/structure/menu/manage/main

On the permissions page /admin/people/permissions I have 'Administer menus and menu items' checked. This worked in Drupal 7.

I can get to the /admin/structure/menu/manage/main page if I manually type in in the browser.

But the 'Structure' button/link does not appear in the toolbar for that role. It shows up for me when am logged in as User/1

How do I get the 'Structure' in the Toolbar? Am I choosing the wrong permission? Am I missing one?

You would have to grant the following permissions to the role:

Required

"Use the toolbar
Administer menus and menu items
Use the administration pages and help

Optional

View the administration theme


Do we have another solution for the "After cloning a node" event for the Node clone module? I would like to use the event in Rules "After cloning a node" but unfortunality this does not work. (see Event "After cloning a node" by node clone module is not working).

I tried to patch the module but did not succeed.

I would like to solve this with rules with :

Event - "Node Edit on type foo"
and then add some conditions.

Does anybody knows a good condition for this? What can I compare?

Are there other solution possible?

I need it for the folowing situation: the user has two options for a node:
(1) Edit
(2) Clone

(1) The edit option is just going to the edit form. Normal editing should be done.

(2) The clone option makes a copy of the Content Type and then starts editing in this node. Before the user is starting this editing two fields in the content type should be empty.

--- Patch log (#8)
$ patch -p1 <2212039-8.patch
patching file clone.pages.inc
Hunk #1 FAILED at 160 (different line endings).
1 out of 1 hunk FAILED -- saving rejects to file clone.pages.inc.rej

--- Patch log (#8) With option --ignore-whitespace
$ patch -p1 --ignore-whitespace <2212039-8.patch
patching file clone.pages.inc
Hunk #1 FAILED at 160 (different line endings).
1 out of 1 hunk FAILED -- saving rejects to file clone.pages.inc.rej

Try to think of a way to better describe what you're trying to do, and for which using that specific event does not work (because of that bug).

Obviously, it doesn't matter what the subsequent Rules Condition and/or Rules Action would be (after you have "an" alternative for that Rules Event you are asking about).

But sometimes the solution for a problem, is to avoid the problem from happening, right? E.g. maybe there is some specific path you could try to intercept (also using the Rules module), right before/after that event occurred. I seem to remember node clone also has such path. And if anything else fails, use Rules Event "Drupal is initializing", followed by a Rules Condition to check such path (if needed using RegEx also ... I bet you know about that Rules trick also).


A really big database size I'm dumping the database every 2 days, but I noticed that at some point last month the database jumped from around 500 MB to 4 GB!

What can be the cause of it?

One reasons that a database can grow w/o bound is when you don't have cron setup to run.  Check your "Recent Log messages" at /admin/reports/dblog  and filter for cron, and make sure it is running (nightly is a good start).

On of the things cron does is prune the cache, watchdog, and sessions tables.  These can fill up quickly with data that isn't critical to Drupal running.

Occasionally, clearing these out can take too long for a cron run.  If this is the case, running a manual query, such as

DELETE FROM watchdog;

may be needed.  As mentioned above, you can run this on the cache and tables beginning with cache_, watchdog, and sessions.  It is always best to take a backup first, before running DELETE queries.


Contextual links don't display in a floated custom region I created two custom regions in my Drupal 7 theme and used CSS to float them side-by-side (to create columns). That worked fine, and I'm able to place blocks in the regions, but the contextual links don't display.

I tested them without the float, and the contextual links are right where they should be, leading me to believe that it's the float positioning that's causing the problem.

This isn't too big a deal, since I can go to Structure --> Blocks to administer them, but the contextual links are handy, and besides, it's bugging me and I want to figure it out. Any suggestions?

Try to add an "overflow:hidden;" to the wrapper of both the content and the contextual links to force it to fill the dimensions of its children. Either that or add a clear as a sibling of the elements. What's probably happening is the wrapper is being rendered to 0 height.


Drupal shows mobile theme on desktop I have drupal 6 with mobile-tools module and idrupal theme for iphones. sometimes my website starts displaying mobile theme (idrupal) for desktop, and the only way to return back to normal theme for desktop is to flush all caches.
is there a permanent solution to disallow idrupal theme from being used for desktop?

If you are using varnish in front of the your server, then it will completly cache you request, Mobile tools will not be able to determine the useragent is mobile or desktop to redirect the theme.

One of the solution is to determine at varnish level and redirect to a m.domain which always has a mobile theme attached to it.

Refer the following links

http://fangel.github.com/mobile-detection-varnish-drupal/
http://mobiledrupal.com/content/mobile-device-detection-varnish-0


How to check a mysql table field type I need to check whether a certain table field is of type 'int' (I am referring to table schema)

e.g. for table field_data_field_myfield
field_data_field_myfield_value  is of type int(11)

I actually need a generic function that check if a certain field is of type in the schema.

[Edit]

I want to explain better my difficulty:

I have a feature that holds a certain field of type 'datetime'. Now as this type creates performence problems on database sides, I decided to change it to 'datestamp' [= unix format]. I did this editing the file MYFEATURE.features.field.inc that is a database field table mirror.

Now the reports are:

FieldException: Cannot change an existing field's type. in field_update_field()

This is an exception raised due to the fact I am not supposed to alter schema while data is in. Therefore I create a hook_update_N for data migration.

Now I believe I need to do a hook_update_N for schema migration too.
HERE is the point I need to alter schema in a hook_update_N.

You want something like:

function _mymodule_is_db_column_int11($drupal_field_name) {
  // See example output below.
  $drupal_field_info = field_info_field($drupal_field_name);

  // From this table you can get the table name, which follows a known
  // convention in the Field API (but this lets you get it grammatically)
  // and also value field names from the definition array.
  $sql_details = $drupal_field_info['storage']['details']['sql'];
  $table_name = key($sql_details[FIELD_LOAD_CURRENT]);
  $value_col_name = $sql_details[FIELD_LOAD_CURRENT]['value'];

  // Then in MySQL check the column type. I see no way to do this using
  // the drupal api.
  $raw_table_info = db_query("SHOW COLUMNS FROM :tbl;", array(':tbl' => $table_name)->fetchAll();

  $is_int11_field = FALSE;
  foreach ($raw_table_info as $result_id => $recObject) {
    if ($recObject->field == $value_col_name && $recObject->Type == 'int(11)') {
      $is_int11_field = TRUE;
    }
  }
  return $is_int11_field;
}

An example of output of field_info_fields() for 1 field:

/*
[field_foo_feedback023] => Array
    (
        [entity_types] => Array
            (
            )

        [foreign keys] => Array
            (
                [format] => Array
                    (
                        [table] => filter_format
                        [columns] => Array
                            (
                                [format] => format
                            )

                    )

            )

        [indexes] => Array
            (
                [format] => Array
                    (
                        [0] => format
                    )

            )

        [settings] => Array
            (
            )

        [translatable] => 0
        [storage] => Array
            (
                [type] => field_sql_storage
                [settings] => Array
                    (
                    )

                [module] => field_sql_storage
                [active] => 1
                [details] => Array
                    (
                        [sql] => Array
                            (
                                [FIELD_LOAD_CURRENT] => Array
                                    (
                                        [field_data_field_foo_feedback023] => Array
                                            (
                                                [value] => field_foo_feedback023_value
                                                [format] => field_foo_feedback023_format
                                            )

                                    )

                                [FIELD_LOAD_REVISION] => Array
                                    (
                                        [field_revision_field_foo_feedback023] => Array
                                            (
                                                [value] => field_foo_feedback023_value
                                                [format] => field_foo_feedback023_format
                                            )

                                    )

                            )

                    )

            )

*/

If you're going to try and use this you'd probably want to add caching, probably want to assure your type check is always forced to lower-case etc. Also check your mysql credentials allow for this sql usage of SHOW.

EDIT: A slightly simpler solution

The only problem I see with this solution is for complex or custom fields you will always have to know what the value field you want to check is; and require a custom check -- for default simple value fields this should work without needing custom SQL:

function _mymodule_is_db_column_int11($drupal_field_name) {
  // See example output below.
  $fields = field_read_fields();
  $my_field = &$fields[$field_name];

  $field_uses_sql_storage = $my_field['storage']['type'] = 'field_sql_storage';
  $field_value_uses_int_11 = $my_field['columns']['value']['type'] == 'int' && $my_field['columns']['value']['length'] == 11;

  return $field_uses_sql_storage && $field_value_uses_int_11;
}


Help with SQL-query finding and updating uid's from non-existing users in comment table I need help to make a SELECT from the drupal database.

Two or three tables

comment
users
node (maybe)

I want to find all uid's in the comment table from former users but where the uid>0 in the comment table. uid's for former users but whom don't exist in the users table.

I also would like to make an UPDATE-script that can set all uid's from non-existing users in the comment table to zero "0".

This will solve some of the search indexing problem, where it stopps at certain nodes.

Please help me.

I think this should do it. Make sure you take a backup before running this:

UPDATE {comments} SET uid = 0
WHERE uid > 0
AND cid IN
(
  SELECT cid FROM {comments} AS comment
  LEFT JOIN {users} AS user
  ON user.uid = comment.uid
  WHERE user.uid IS NULL
)


Where can i find buildRow parameter? in EntityListBuilder::buildRow we can define row like below:

$row['title']['data'] = array(
    '#type' => 'link',
    '#title' => $entity->label(),
    '#suffix' => ' ' . drupal_render($mark),
    '#url' => $uri,
  );

question is: where can i find list of the options/parameters documentation of this? (#type, #title, what is the other possible option?)

This is the render element Link, which is used to make the title clickable. The non linked version would look like this:

$row['title'] = $entity->label();

You can use any render element or a nested render array.


empty page creation and filling it with blocks I need to create a custom page which content region can be nicely presented as a set of views blocks. I don't know whether it's possible. So the question is:

Is there any possible way to create an empty page with certain url , e.g. "mysite.org/news", and fill its 'content' variable  with some blocks without writing a module and declaring the page with php and hooks? Just from the admin interface.

Seems like Panels would be good for this. You'd create a panels Page and then assign the relevant blocks.


Installed Boost Caching, but now my dynamic blocks and webforms are also cached I just installed Boost module for Drupal 7, but now my Webforms and dynamic blocks like commerce shopping cart block isn't working. It's most likely cached, but what are some methods of getting these dynamic blocks to work? I already added exclude paths for admin/*, user/* and checkout/* so it doesn't cache those pages.

It seems you  check Cache blocks(block caching) in config/development/performance.
Try to uncheck that. When you work with Boosts it is not require use that feature.


Customizing a drupal webform for Drupal 6 I am working on a system that would require users to register online by filling out a membership application form. There used to be a PDF form that used to be filled out and sent for processing. The client wants the online form to be as close in appearance to this PDF form. Is it possible to customize a form created using webforms such that it can have some of these elements such as logos, images, etc.?

You can customize form's HTML markup using Drupal's form alter hooks:

hook_form_alter or hook_form_FORM_ID_alter
Form API Reference

after changing form's markup you should only styling form using CSS.


How to choose a mentor on drupal.org Sorry for the off topic question, it may seem in wrong direction as it is not relevant to coding and other stuff.

The problem is that I am developing a module called Amazon send to kindle.
It is right now in sandbox module. I am getting problem, as i am not able to share on amazon kindle.

I need a guidance from some expert users, to help and guide me in the development. Drupal.org allows us to select the mentors, but i don't know how should i approch other user to be my mentor.

Is there any official way to ask users to be my mentor ?

There is a posting from Dries Buytaert titled Drupal mentors needed, where he basically asks senior people to become mentors ("Find, motivate, guide and empower people to take on a role within the Drupal community").  So if Dries is the official voice of the Drupal community (and I suppose he is), you're supposed to hang around until some aspiring mentor finds you :-(.  Unfortunately, this very rarely gives the prospective student access to a mentor.

There has been some attempts from other community members to improve on this situation.  For instance, there is the Drupal mentor group. with first and last posts in October 2010 (and one spam post from 2012).  You could try to introduce yourself there, but the group seems to be dead.

There is also Drupal Kitchen.  There is a handful of people signed on to the site as tutors, but to me, this site looks like yet another failed effort.

If you want to learn how to contribute to the core, there is core contribution mentoring. It uses @drupalmentoring (twitter) to set up office hours and sprints for mentoring aspiring core contributors. This may be educational, but is very much oriented towards the core contribution workflow, and not suitable for learning about Drupal in general-

Here is what I suggest:  Start by getting a user account on Drupal.org and Groups.Drupal.org (unless you've already done so).  In Groups.Drupal.org, look for groups in your geographic area. Join those groups and try to find someone local to communicate with, and look for local meet-ups and sprints you can attend.

Also, use this site (Drupal Answers), the forums on Drupal.org, and IRC to ask specific questions about the problems you have developing.  You will not get a specific mentor, but you will usually get relevant help from the community.

However, in my experience, when developing a module, the best way to get the attention from senior members of the community ("mentors") is to join the Review bonus program.  This requires some effort on your part, since you're supposed to mentor others (by reviewing their modules) -  but you learn a lot from doing so!  Do not be afraid of being a novice reviewer.  You'll get feedback from the other reviewers about your reviews.   It is OK to make mistakes, and you'll learn from them.


Unable to set the data property xxx as the parent data structure is not set I currently use geofield to set latitude and longitude but rules gives me this error:

0 ms Unable to modify data "user:field-coordonnees:lon": Unable to set the data property lon as the parent data structure is not set.

So values are not set and I do not understand why, it's just a set data.
The value exists because I can see it in a "Show a message on the site". I've also tried to cast the value as Integer, nothing has changed.
Any idea ?
Configuration:

Geofield Map 7.x-2.3
Geofield 7.x-2.3
geoPHP 7.x-1.7

I've found the issue.
In fact insted of set a lat and a lon value, I had to use "Create geofield values from lat/lon".


Facebook auto post module not posting to my FB page When user comments on a particular node the comment title and comment body should be automatically posted to my Facebook page. For this I have used Facebook autopost. I have added my appid in fb_autopost configuration page and it displays the list of pages I manage and I have selected required page. Used below rules for auto posting comment in facebook

{ "rules_facebook_autopost_" : {
    "LABEL" : "Facebook Autopost ",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "fb_autopost_entity", "comment" ],
    "ON" : { "comment_insert--comment_node_theme_display" : { "bundle" : "comment_node_theme_display" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "facebook_publication",
            "param_type" : "link",
            "param_user" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-facebook-message" ],
          "value" : "[comment:title]"
        }
      },
      { "publish_to_facebook" : {
          "USING" : { "publication" : [ "entity-created" ], "pages" : "1575855786569558" },
          "PROVIDE" : { "facebook_publication_id" : { "facebook_publication_id" : "Facebook publication returned ID" } }
        }
      },
      { "drupal_message" : { "message" : "success" } }
    ]
  }
}

After saving the comment it throws below error and comment not posting in Facebook.

  Facebook SDK threw an error: OAuthException: (#200) The user hasn't
  authorized the application to perform this action

How can I achieve this or Is there any other way to do this. Thanks

Finally found the answer.

In admin/config/services/fbpermissions need to give Publish pages permission for users.


Unable to fetch image after using Content Import and IMCE module I am trying to import content for custom content type fields using csv, in content I have images fields as well and using the Content Import Module for CSV import and IMCE module for image upload. After import CSV all content showing but images not showing. The path for images also storing in file_managed table
I have set the permission of the folder still its now showing the images

Also place the image in the /sites/default/files/artist/hero
Please help with this problem?

Your folder path should be "CONTENT-TYPE MACHINE NAME/images" not artist/hero and set permissions to 777 as per Content Import Module. And also change File directory path under that field as "CONTENT-TYPE MACHINE NAME/images".


Voting Api + Vote Up / Down = Vote Power I have installed VotingApi with Vote Up/Down, also have my own module which implements user exp and levels. I want the voted to be more powerful if the user has greater level. I search through Vote Up/Down files but didnt find a file inserting the vote to databse, so I could change it depending on my needs.

The vote will be casted by calling the Voting api function votingapi_set_votes(). But if you want to change the votes before sending it to Voting api there is hook for this called hook_vud_votes(&$votes) which you can use.

Update:
The api file mentions a hook called hook_vud_votes(&$votes) to alter the vote but in their code they are invoking the hook using drupal_alter(), so the right hook to implement is hook_vud_votes_alter(&$votes), I think it is mistake in their api doc.


Adding attributes to a link to an uploaded file I have been asked to add target="_blank" to the links that are produced when a user uploads a file on a Drupal 8 site.
The field type is "File". Multiple uploads are allowed.
Twig debug shows me that the field is being produced by the core template "file-link.html.twig". The entire uncommented contents of that template are:
{{ link }}
{% if file_size %}
  {# @todo remove class before Drupal 9.0.0 #}
  ({{ file_size }})
{% endif %}

I brought that template into my custom theme and tried to add the attribute to the link. I thought I'd be editing the {{ link }} part of the template, changing it to attach attributes. I did variations of this:
{{ link(item.title, item.url, attributes.setAttribute('target','_blank')) }}
Every syntax I tried produced a fatal PHP error. Thinking I was doing the attribute syntax wrong, I tested  by simply trying to add a single class.
{{ link(item.title, item.url, { 'class': ['bananas'] }) }}

That was still a white screen of death, so I guess I can't use that syntax on the {{ link }} field in my file-link template.
I've been googling my eyeballs out of my head. I found this cool idea:
{% for item in items %}
  {{ item.content|merge({'#attributes': {'class': ['button', 'button--arrow', 'button--centered']}}) }}
{% endfor %}

so I adapted it for my field.html.twig template like so, changing this part:
{% for item in items %}

{{ item.content }}

{% endfor %}

to this:
{% for item in items %}

{{ item.content|merge({'#attributes': {'target': ['_blank']}}) }}

{% endfor %}

And while at least the page loaded and didn't have a fatal error, the target attribute did not appear on the link.
Does anyone have any advice for me getting an attribute onto a file upload link? Almost everything I've found has to do with the link field, not the file upload field. Thanks for your time.

file-link.html.twig
{{ link|merge({'#attributes': {'target': '_blank'}}) }}
{% if file_size %}
  {# @todo remove class before Drupal 9.0.0 #}
  ({{ file_size }})
{% endif %}

Alternatively, you can also solve this via preprocess.
mytheme.theme
/**
 * Implements hook_preprocess_HOOK().
 */
function mytheme_preprocess_file_link(&$variables) {
  $variables['link']['#url']->setOption('attributes', ['target' => '_blank']);
}


Adjusting Main Menu Tabs I am able to add tabs in the Drupal 7 Main Menu however I want to adjust spaces between these tabs.How does one adjust spaces between tabs.

Thanks

Website styles in general are coded through CSS.

Drupal implements that through themes. If you're using the default Bartik theme you can override the navigation item spacing with the margin property on the list items.

It's not recommended to modify an existing theme file if you need to adjust its style. The best practice is to create a subtheme based on the original and include the modifications in the subtheme so they override the original one.

If you're not knowledgable in themeing or CSS you can make small CSS adjustments with the help of a module like CSS Editor. This way you don't have to worry about themes or subthemes, the code will always apply.

You can try something like:

#main-menu-links li {
  margin-right: 20px;
}

You may have to clear your CSS cache in Drupal to see the changes, if you have the CSS aggregated under Performance.


Rules: after saving new content and after updating existing content both triggered on node create I define two rules that should send an email once new node has been created. And second rule once user updated his content.

The problem I am having here is that both rules trigger in one time when your create a new node.

I found the same issue has been asked in anther question but not very clear and i am not able to understand enter link description here

But I am not able to understand.

Thanks for the help.

This is very easy to accomplish, you have a few attributes of the node to compare and check in order to decide which trigger to be true/false.

Method 1:
Put the following PHP code into your both conditions (create & update) by selecting execute PHP code

CREATE

if($node->created == $node->changed) {
   return true;
} else {
   return false;
}

UPDATE

if($node->created != $node->changed) {
    return true;
} else {
   return false;
}

Method 2:

UPDATE:

if($node->is_new) {
     return false;
} else {
     return true;
}

OR

if(!empty($node->nid)) {
    return true;
} else {
    return false;
}

I have not checked the Method 2 but, method 1 is easier and should definitely work out for you.

Don't forget to Accept this answer solve your problem.

Cheers.

Raf.


Different behaviour saving programatically vs UI I am having a problem saving nodes programatically.  I am attempting to save nodes that use the following pathauto pattern for an alias:

[node:og-group-ref:0:url:relative]/[node:menu-link:parents:join-path]/[node:title]

Both the first and last token work fine both ways.  However, the middle token - [node:menu-link:parents:join-path] - returns empty when saving through a script and populates fine when saving through the UI.

I've inspected $node object that is being passed through in each case and they are identical, except for $node->path.  When saving through the UI the $node->path value looks something like this (copied from devel dsm message):

[path] => Array
    (
      [alias] => communications/some-person
      [pid] => 153
      [source] => node/100
      [language] => und
      [pathauto] => 1
    )

However, when saving programatically $node->path looks like this:

[path] => Array
          (
            [pathauto] => 1
            [alias] =>
          )

As you can see, its missing data that is present when saving through the UI, and I suspect that data is needed to correctly parse the token.

Anyone have any idea why these two would be different or why the [node:menu-link:parents:join-path] token doesn't work when saving through the script?

If it matters, script is pretty straight-forward:

<?php
$nids = db_query('SELECT nid FROM {node} where nid = 100')->fetchCol();
foreach (node_load_multiple($nids) as $node) {
  echo "Saving node " . $node->nid . "\r\n";
  print_r($node);
  node_save($node);
}

Thanks in advance.

For anyone that might find this in the future, this is related to this issue:

http://drupal.org/node/1534356

Still trying to figure out a workaround for my scenario, but this is the cause.


db_select with groupBy(CAST(column as DATE)) I am looking to achieve GROUP BY CAST(date_time AS DATE) in a db_select function in Drupal 7 but with no idea how.

The function up until now is:

 foreach ($distinct_users as $user){
    $day_record = db_select('mytable', 'p')
      ->condition('p.processed', 0, '=')
      ->condition('p.first_name', $user['first_name'], '=')
      ->condition('p.last_name', $user['last_name'], '=')

and I need to group the results by day which is in Y-m-d H:i:s in my table column.

Please advise.

The solution that worked for me was to group results via php.


How do I create a taxonomy tag from node title I have a "Tags" vocabulary, and I would like to automatically add the node title to this vocabulary as a tag on saving the node. I have tried to use the Rules module to do this, but I can't get it to work.

Can you help me?

I wouldn't recommend you doing that, you might get crazy node title names like "hello world I love peaches" and you dont want that tag.

anyway you can do a Hook_node_insert in your custom module to add your code after creating a node, then you should use taxanomy_term_save to insert your new term.

let me know if you need more on this.


How to make disqus load avatar picture instead of user picture? In user profiles I created a field called Avatar with a machine name of field_avatar.

I was wondering if I could make Disqus load the Avatar picture instead of the default Drupal user picture.

Here is the default Disqus code

        // Load the user's avatar.
    $user_picture_default = variable_get('user_picture_default', '');
    if (isset($account->picture) && !empty($account->picture) && is_numeric($account->picture) && $file = file_load($account->picture)) {
      $data['avatar'] = !empty($file->uri) ? $file->uri : NULL;
    }
    elseif (!empty($user_picture_default)) {
      $data['avatar'] = variable_get('user_picture_default', '');
    }
    if (isset($data['avatar'])) {
      $data['avatar'] = file_create_url($data['avatar']);
    }
  }
  drupal_alter('disqus_user_data', $data);

  return $data;
}

As seen in above code you can use disqus_user_data_alter hook to change disqus data in your custom module...

function YOURMODULENAME_disqus_user_data_alter(&$data) {
  global $user;
  $user_picture_default = variable_get('user_picture_default', '');
if (!empty($user->field_profile_picture[LANGUAGE_NONE][0]['fid'])) {
  // Load the file -- Change field_profile_picture with your field name
  $file = file_load($user->field_profile_picture[LANGUAGE_NONE][0]['fid']);

  // Note the style name is "profile_picture" as explained in your question,
  // not "profile_pic" which was in your original code
    $data['avatar'] = !empty($file->uri) ? $file->uri : NULL;
  }
  elseif (!empty($user_picture_default)) {
    $data['avatar'] = variable_get('user_picture_default', '');
  }
  if (isset($data['avatar'])) {
      $data['avatar'] = file_create_url($data['avatar']);
  }
}


Alternative to SQL Server for mySQL I'm new to the open source world (use to be all Microsoft). I've just installed Drupal on my mac, and I'm wondering which program is a popular choice for making changes in mySQL?

I can see that changes can be done in Terminal (bash) but I would have should there is an easier way. Do most people use the command line, or a GUI program?

PhpMyAdmin is by far the most popular tool for managing MySQL. It is a webapp which is simple to install and lets you do most tasks through a GUI.

There are many alternatives, notable Chive (more shiny, ajax based tool) and Adminer (more minimalistic). If you want a stand alone application, Sequel Pro might be worth a look.


View to show 2 different fields that have multiple values next to each other I have a content type that has 2 fields on it:

image (multiple values)
image description (multiple values)

I have 6 images and 6 descriptions. I want to use a view to show each image with each description. I have tried playing around with the "Display all values in the same row" settings but just can't get this to work. It displays the same image repeatedly (6 times) and then the descriptions are all correct, then repeats the next image 6 times again.

I am tearing my hair out here, how do I get a view to simply out output:

Image 1, Description 1
Image 2, Description 2

and so on?

I have included an image of current output plus the way the fields were set up on the node. I have set them up this way as I need to import a lot of them.

As commented there might be better data models. But in case you can't change the data model it's probably the easiest solution to switch the View to display content in a view mode and display the field deltas in a node template:

node--content-type--view-mode.html.twig

{% for key, item in content.field_image if key|first != '#' %}

  {{ item }}

  {{ content.field_description[key] }}

{% endfor %}


How do I re-import menus and blocks? I've got a local install that has turned bad. I want to quickly re-import block settings, block content, and menus.
How can I achieve this?

You can export blocks with the Features Extra module, or better yet, use the Boxes module, which is designed to be exportable.

Using MySQL dumps is an advanced trick that gets harder with each version of Drupal as the API becomes more complex. It's not recommended and definitely not for the faint of heart.


Drupal 7, Ubercart, Product search by price range I'm using Ubercart 3.x, Drupal7. Can anybody tell me how can I create a form for searching in products with price in specified interval? I.e. user should fill this form with minimum price in the interval and maximum price and after posting form he will see all suiting products.

There are two ways of doing it:
One is using views and 2 price exposed filters, one with  "value bigger than" and the other one with "value smaller than".
The other solution is using Search API ranges module.

The Search API "ranges" module provides widgets for Search API range queries. Currently includes:

jQuery UI min/max slider.

To use it, you will need to use Facet API, follow a tutorial here.
I hope this helps you


How do I load all images and thumbnail for a multivalued image field in node view? I have a content type with a multivalued image field. I want to make the image field render with one main image and all the thumbnail. When any of the thumbnail is clicked then it's respective image takes over the main image section. Something like amazon product images.

What I have thought about so far is to create a preprocess function for the field to load all images along with all the thumbnail then, with custom CSS and JS, customize its rendering, is this the right way to go about it? And how do I load all the thumbnails for the image field in node view?

You can use galleryformatter and then a bit css if you want


Using tokens or variables in Views "No Result Text" field How can I include a variable or token as a replacement in views "No Results Text"?

I would like to have information from the currently logged in users account populate this section when it would have otherwise been empty.

I would also like to access the second argument passed in the URL as replacement text.

example/values/passed/to/views

How can I use arg(2) as replacement text in views?

Here is how I'm hoping to use the UID:

As I understand, in that field you should be able to use only fields and arguments tokens provide by Views only.

Unfortunately you can't use regular tokens  on that field. Maybe you should ask this directely on that issue your request to add support of tokens (that make sense actually).


How to list only the latest revision of all nodes in a view? I currently have a view that lists all of our nodes which is what we use for a content dashboard. It shows the most recently updated nodes, their workflow status, and a few other details.

The problem we seem to be having is that we're using Revisioning which creates a new pending revision each time a user updates a node. When a user updates a node, the workflow state (custom CCK field) switches to Review automatically. Since the current published node has the workflow state Live, the view's workflow field does show "Review". I'm assuming this is because the view is only pulling the currently published content and not the pending revisions content.

When using the view type Node Revisions it lists every revision of a node, not just the latest one. This is a problem because our dashboard would be filled with a single node's revision history instead of all the current nodes.

Is it possible to create a view that lists only the latest revision (pending, or current) of all nodes on our site?

Version info
Drupal 6.22
Views 6.x-2.12

In the view you should have it sort by revision id (vid) descending, then use Views Group By to group by node id (nid).


Can a Drupal view show some fields for one role and other fields for another role without having two page views? I need to create a view showing the history of the users events. I need the authenticated users to be able to see part of the view, certain fields, and the admin to see all fields in the view. The fields are user_id, activity_id, title, status. I need the user_id and activity_id to be hidden from the authenticated user but not the admin. I know how to control the whole view but not fields in that way.

Has anyone tried to manage that? Is there a way to do this?

You can add all the fields to the view and than hide some of them in either a hook, a preprocess function or a template file.

There views module provide many hooks for you to use i suggest the views view pre render hook.

If you choose the preprocess route than you will need to find the correct template first. Go to the view configuration page and look for a link called theme info. That link will be placed in the advanced column at the very bottom.

After you know which template you need add the corresponding preprocess function to your THEME.theme file.

Fit the views-view-unformatted.tpl.php a function called THEME_views_view_unformatted_preprocess will work.


Using computed field to calculate total hours for a datetime field but to exclude all weekend hours Please please if can anyone help I would really appreciate it!

I have managed to get total hours between value 1 and value 2 of my datetime field however I really want to exclude any hours which are in the weekend. I am creating a timesheet for a group of carers and some people will work from a friday night to a saturday morning etc.

this is my code I use atm for calculating the total hours:

$start_value = $entity->field_work_hour_date[LANGUAGE_NONE][0]['value'];
$end_value = $entity->field_work_hour_date[LANGUAGE_NONE][0]['value2'];
$timezone = $entity->field_work_hour_date[LANGUAGE_NONE][0]['timezone'];

$start_date = new DateObject($start_value, $timezone);
$end_date = new DateObject($end_value, $timezone);

$duration = $start_date->difference($end_date, 'hours');
$entity_field[0]['value'] = $duration;

I am still quite new to drupal and php so I would really appreciate any help.

Cheers

I would :

$duration = $start_date->difference($end_date, 'hours');
// Place this :
if($start_date->format('Y-W') != $end_date->format('Y-W')) {
  $difweeks = $start_date->difference($end_date, 'weeks');
  $duration = $duration - intval(48 * $difweeks);
}
$entity_field[0]['value'] = $duration;


redirecting to url that will never complate i used this code to redirect page to another

$path=$_SERVER['QUERY_STRING'];
$new_path= 'http://localhost/mysite/print/194?0=' . $path;
drupal_goto($new_path);

but when requesting that page this error show up:

and the url in the address bar is:
http://localhost/mysite/print/194?0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=f1=All&f2[value][year]=&f2[value][month]=
but when i print the $new_path using drupal_set_message the url looks like correct one
Can you help me to solved it? thanks.

The biggest issue is that the query string should be passed in separate from the base URL itself, eg, it should be part of the $options array argument to drupal_goto().  Otherwise, as you've noticed, drupal_goto() doubles up a lot of times.  If you fix that, I am fairly confident that you will get it to work.

Check out http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_goto/7
and
http://api.drupal.org/api/drupal/includes%21common.inc/function/url/7
for more information on this.


How to create a view to display event registrants? I'm having troubles setting up a View that displays a list of registrants (not registrations!) for a particular event. I don't know how to setup RELATIONSHIPS correctly?

(I have already created a view that displays all registrations for a particular event, but since the user can register more than once for a particular event, I'm getting a list with multiple users enteries (if user registered multiple times) which is not what I want.)

Any suggestions?

For displaying user entries only one, open the  Query settings: Settings located at bottom of the Advance section.
There u can check the Distinct checkbox which will make the view display only distinct items.

Hope this help you...


Webform Submission Count using views I am trying to create a view that will count the number of submissions that a particular webform has.

So far I have added the field:
Webform: Webform submission count

and added in a Node:ID filter to the ID of my webform.

When I preview the webform it works fine, however when I place the view on my front page it returns 0 results.

I am thinking this is because anonymous users don't have permissions to access submissions? Which I don't particularly want them to anyways.

The field also links to the submissions page of my form, which I don't want it to do either, i just want text there. I have checked the settings and there is nothing to say that the field should link to the submissions.

Bottom line, how can I create a view or perhaps if there is a count module, that will show the number of times a particular form on my site has been submitted?

Thanks! :)

For removing the link all you have to do is click on REWRITE RESULTS
Then click on "Rewrite the output of this field"
and then check "Strip HTML tags" That should remove the link.

The easiest way to achieve the other one is a bit of a hackish solution. You need can go to webfor/views folder and look for the file webform_handler_field_submission_count.inc

with in that file check for the render function.

  function render($values) {
    global $user;

    $output = NULL;
    if ($this->count_type == 'node' && in_array($values->{$this->aliases['type']}, webform_variable_get('webform_node_types'))) {
      module_load_include('inc', 'webform', 'includes/webform.submissions');
      $node = node_load($values->{$this->aliases['nid']});
      //if (webform_results_access($node, $user)) {
        $count = webform_get_submission_count($node->nid);
        $output = l($count, "node/$node->nid/webform-results");
      /*}
      else {
        $count = webform_get_submission_count($node->nid, $user->uid);
        $output = l($count, "node/$node->nid/submissions");
      }*/
    }
    elseif ($this->count_type == 'users') {
      $output = db_select('webform_submissions')
        ->condition('uid', $values->{$this->aliases['uid']})
        ->countQuery->execute()->fetchField();
    }

    return $output;
  }

In this above code I have commented a section. You can do the same it should work now for anonymous user. As I said this is a hackish solution and wont advice to do the same. The cleaner method would be to create a custom module and add the handler you want in the custom module and use that instead.


How to hide custom fields on the menu item form? I've added two new fields to the menu item form (admin/structure/menu/item/{ID}/edit):

function modulename_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  $fields = [];

  if($entity_type->id() == 'menu_link_content') {
    $fields['show_mobile'] = \Drupal\Core\Field\BaseFieldDefinition::create('boolean')
      ->setLabel(t('Show in mobile menu bar.'))
      ->setDescription(t('Toggles the display of the menu item in the menu bar at the bottom of pages in mobile view.'))
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'weight' => '0',
        'settings' => [
          'display_label' => TRUE,
        ],
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['svg_icon'] = \Drupal\Core\Field\BaseFieldDefinition::create('string')
      ->setLabel(t('Mobile Menu Bar SVG Icon'))
      ->setDescription(t('Select the icon you want the menu item to use in the mobile menu bar.'))
      ->setDisplayOptions('form', [
        'type' => 'string',
        'weight' => '0',
        'settings' => [
          'display_label' => TRUE,
        ],
      ])
      ->setDisplayConfigurable('form', TRUE);
  }

  return $fields;
}

But now I run into the issue, that I only need these fields for the main navigation menu, and thus want to remove or hide these on all other menu item forms.

Preferably I would like to keep it all to the module that adds the fields, and not have to create a custom admin theme just to visually hide them.

What should I look at to figure this one out? I've tried googling a lot of different combinations of the question, but have yet to find anything that remotely looks like a solution.

Many thanks in advance to anyone who can point me in the right direction.

hook_entity_base_field_info will add fields to the entire entity. If you want to hide the fields in specific forms, you will have to use a form alter to hide the fields. The following code might be what you are looking for.

/**
 * Implement hook_form_FORM_ID_alter();
 */
function modulename_form_menu_link_content_menu_link_content_form_alter(&$form, FormStateInterface $form_state) {
  $name = $form_state->getFormObject()->getEntity()->getMenuName();
  if ($name !== 'my-menu') {
    $form['show_mobile']['#access'] = FALSE;
    $form['svg_icon']['#access'] = FALSE;
  }
}

Change my-menu with the menu machine name of the only menu that you want the fields to appear on.


trailing slash added unwillingly and page not found There is a url that links to a view that is a page. When clicking the link to that view, a trailing slash gets added and the the page returns 'page not found' nothing about the site gets loaded, just this string as if it said die('page not found') first thing on load.
It wouldn't matter if I would manually type the correct url, the trailing slash would be added as well and return the same page not found string.

The only module I could find was global redirect. This module has checkbox in its settings that says 'Deslash'. I tried unchecking - save and checking - save again, but no help.

There was a folder in drupal installation folder with the exact same name as the path, which added the slash at the end


Copy installed modules and configuration to new installation I have a Drupal 8 application with mysql as database. I installed bunch of third part modules such as domain, search_api, pdf etc... Most I installed using composer and a very few using "Install module".
Configured few content types, created few views, pages, configured apache solr for search indexing...

Now I have requirement to set up everything in a higher environment using oracle as database. I was able to setup a blank drupal 8 application with oracle database.

Question: Installing all the modules in new installation ?
My thoughts -> Edit the composer.json to add modules and run composer update and  manually install rest of the modules or Is there a better way to import all the installed modules to new app.

Question: Configuration migrate ? I was thinking of using configuration > development > Configuration synchronization to export and import all the configurations.

Question: Data migrate ? I used migration module to import content and upload files. If everything works till here, data migration is the last priority. Good to have. I have one custom module too created for migration purposes. I used this migration module to migrate csv data to druapl8-mysql application. If everything works, I want to migrate the same csv content to drupal8-oracle application.

This exercise will help us to migrate and duplicate setup to test environments too. Please suggest an ideal process for the migration.

Question: Installing all the modules in new installation

Answer: Yes add all modules to root composer.json file so only have to run composer install or later composer update

Question: Configuration migrate

Answer:
Configure your sites sync folder 'in settings.php' and run drush cex to export the current sites config (then you can git commit the changes and deploy to new environment) and run drush cim on new environment to import changes.

Question: Data migrate

Posable Answers:
now this one can get kinda tricky and have a lot of options for this ... which depends largely on what you want to keep / what you don't.

Simple option: copy database - good old fashion export database and then import it.

Content migration option: look in to https://www.drupal.org/project/default_content_deploy  its like config import/export only for entity data (which again can be commited to repo and deployed) eg drush default-content-deploy:export and  drush default-content-deploy:import

use normal migrate api option.
use a seed database option.

really should just have all the stuff you need in a git repo then you just tag the release ... push to the environment and run some commands or have some automated scripts to run the commands for you
look in to stuff like...
https://chromatichq.com/blog/drupal-8-deployments-jenkins-github-slack
and https://hernani.pt/automatic-update-drupal8


How to display DB data from Custom module using custom HTML markup? I am putting a custom module together. It will take data submitted from a form from site users and store it in the DB. Admins will then be able to review the data and make changes to it. It is easy enough to display the DB data with something like:

return theme('item_list', array('header' => $header,'items' => $rows));

But I need to customize it to have custom HTML markup. Any thoughts, answers or direction?

There are 2 ways of doing it.
First one is to define your own theme function using hook_theme and then either create a theme function of a template file inside of your module or theme folder.
example code is given here

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {
  $custom_theme = array();
  $custom_theme['my_new_theme'] = array(
    // example theme template register
    // for
    //sites/all/modules/mymodule/templates/my_new_theme.tpl.php
    'template' => 'my-new-theme',//dash will convert to underscore in template name.
    'path' => drupal_get_path('module', 'mymodule') . '/templates',
    'variables' => array('header' => null,'rows'=>null),
  );

  return $custom_theme;
}

You can then use

theme('my_new_theme', array('header' => $header, 'rows' => $rows));

instead of your theme function call.
And then inside of your my_new_theme.tpl.php you can access $header and $rows variables.

Second method is not recommended but a possible way of doing this.
So you can just create your HTML output in your callback function where you are creating that list. Store your full html to be out-puted in some variable and finally just return that variable at the end. Drupal will render your HTML as it is.


Replace email address with word "email" Using the email module, you only have the option of outputting the email address as a link, the email address as plain text, or a link to a web form. What I want is to just print the word "email" as mailto link.

For example: In display suite using the link field formatter, you can opt to use the label as the link so the website displays the word "website" which is a hyperlink to the actual url. Is their anyway to do this with email?

It looks like you want to have one more custom field formatter. In order to create a custom field formatter all we need is implementation of 2 hooks

hook_field_formatter_info() - to tell drupal about a new
formatter for a field type
hook_field_formatter_view() - this    is handler for how the field will look like.

so code will be like this

/**
 * Implements hook_field_formatter_info().
 *
 */
function mymodule_field_formatter_info() {
  // Add a setting to a formatter type.
  $formats = array(
    'email_custom' => array(
      'label' => t('Email Custom'),
      'description' => t('Display the email address as custom format.'),
      'field types' => array('email'),
    ),
  );
    return $formats;
}

/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  switch ($display['type']) {
    case 'email_custom':
      foreach ($items as $delta => $item) {
        $output = l("email", 'mailto:' . $item['email']);
        $element[$delta] = array('#markup' => $output);
      }
      break;
  }
  return $element;
}

after adding this codes to your custom module clear the caches and you will see one more field formatter as Email Custom(you can change the labels in above code). Now your configurations in manage display for this field will be .

  Hide your field label
  Select Email Custom as field format


Modify the date popup to only accept special days I may need your help please. I have installed the "Date" module and using it with the date popup (datepicker). I need to have the popup just accepting Wednesdays and Fridays as dates.

Can anybody give me some help on this issue?

Thanks alot!

You can use Date Restrictions in conjunction with Weekdays to acomplish this.

Just download both projects and enable weekdays_date_restrictions module. Then edit the date field and go to "More settings and values" > "Date Restrictions" > "Allowed values" > Choose restriction type: weekdays.


How to pass contextual id value from one view page to another through Drupal menuing system I use a view to display a list of books.
The view has three pages: /books/title, /books/date, and /books/popularity.
The pages are essentially the same with different sort criteria.
The pages use a contextual filter to select books by topic based on a taxonomy.
The contextual filter is set to use the query parameter topic when the filter value is not in the URL.
Each page of the view includes a Drupal menu block with the items "By Title", "By Date", and "By Popularity" and links /books/title, /books/date, and /books/popularity.
If I invoke /books/title?topic=5 (where 5 is the tid for the "health" topic)

A list of health books is correctly displayed.
The "By Title" <li> element in the menu is given the active and active-trail classes by the menuing system (which allows the use of CSS to highlight the active menu entry on-screen).

When I'm at /books/title?topic=5 and click the "By Date" menu entry, /books/date is invoked, so the topic id 5 is not passed to the "By Date" view (unsurprisingly), resulting in a list of all books sorted by date instead of just health books sorted by date.

QUESTION:

How can I pass the contextual filter value (5 in this example) from one page to another via the menu? For example, if at /books/title?topic=5 I click "By Date", I want to go to /books/date?topic=5. How can I set that up?

NOTES

This post is similar to an earlier one where I asked how to get the value coming through the contextual filter. I solved that. There is a twig variable available, in this case, {{ arguments.field_topic_target_id }}.
I used this twig value to rig up my own menu. But having done that, I find that I need the goodness of the Drupal menuing system, both because it makes it easy for editors to change menu items and because it handles the addition of the active and active_trail classes to the proper menu entry.
I have read and tried dozens of approaches to passing the filter value received on to another page via a menu, but none have been effective.

BONUS

Assuming this problem can be solved, I'd really like to use clean URLs. So instead of /books/title?topic=5 I want to use /books/title/5. This works to correctly display a list of health books sorted by title, but when used, the menuing system does NOT set the active and active_trail classes on the active menu <li>, which I need it to do.

The "connected" exposed sorting criteria is implemented in the Facets module and Search API.
Here's a tutorial that can help get you started: Creating a Faceted Search View in Drupal 8 using the Search API Modules

Before you start testing new modules maybe the "ordinary" Exposed Sort criteria in Views can help. Create only one Page display, but add all 3 Sort criteria you want and Expose them. You can use the Expose form in Block to show those options in some region of your theme instead of above the results.

The Better exposed filters module allows you change the widgets from drop-downs to Radio buttons or links. You can also rewrite the filter options to make them more relevant for your cases, and combine the "sort order" with "sort by".

Having an exposed form block can serve like Menu items, showing the user what has been selected, which is what the active menu trail does.

To clean up the URLs there is the Query Parameters To URL module but it's still being ported to Drupal 8. (Help advance it if you can.) Without it I guess you can set up some path redirects manually, although it might be tedious if you have a lot of combinations to cover. You can do that in .htaccess or with the Redirect module.

Yet another approach I can think of is the Views Global Filter module. You might use the "topic" globally, then sort links might work with menu trails (I haven't tried it).


how to display a gallery of custom themes I would like to set up a gallery of all my themes and when the user clicks on the item it would go to a pre-setup Drupal instance and it would set that instance with the theme they clicked so they can see the theme in action. I know how to create a photo gallery but i want to have the images when click go to a sub site that is preset to change the default theme to the one passed in the link so that the user can see the live theme. I would like to have one sub site and have that sub site have all the themes installed and simple change the enabled theme based on the request. The user clicking on the images in the gallery will not be logged in. I don't want to make a different site for each theme. That would be to much unneeded work and to many databases that do not need to be. using modules would be the best over making custom code for this.

The ThemeKey module would help you to achieve this.

  ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules.


Write anything as an author name on an article I need to make it so the author field when making an article doesn't reference actual users. Is this possible without clunky workarounds? The problem is I often have articles posted that aren't posted by an actual user, but their names still need to be credited.

How do I do this in Drupal 7?

Create a field that allows a user to enter text.
Implement a preprocess function that changes the values available to node templates (see the source code of template_preprocess_node() for a list of
available variables).
In the preprocess function, change $variables['submitted'] using the field you defined.

To use the already existing author widget, you would have to implement hook_form_alter() such that it removes the validation function from the form.

Now that the validation function is removed from the form, you also need a way to validate the node. For this, you can add your own validation function. This validation function would temporarily set the author field to a valid value and then call the original validation function.

You also need a new column to store the entered value in the database. The original column is not suitable, because it only holds integers. You also have to add an extra submit handler to the form, so that your data actually gets saved.

So yes, it is possible to use the author widget. But I advice against it. You will lose the information who really created the node. You have to manually deal with loading and saving the entry. And you are giving a well established widget a different meaning.


Clearing contextual links'cache I'm  listing nodes in a block view which is located in a panel managed by page_manager.

I need for these nodes somes custom opérations in contextual links, so i implmented hook_contextual_links_alter() to add some operations.

All works.

Problem : my custom contextual links are appearing in new nodes of this list (or modified nodes) but not in old ones. To make them appear, i need to flush my browser's cache (i'm also using memcache).
Editing all these nodes or clearing browser's cache are the only ways i currently found to get contextual links working for old nodes.

I need to achieve this during the update of my app with hook_update of my module without editing all these nodes or asking users to clear their cache.

PS : i tryed to clear all cache with & without drush -individually or not-, by all ways, all modules are last stable version, drupal 8.5.2

This cache is located in sessionStorage on modern browsers.

I'm just clearing the entire sessionStorage with window.sessionStorage.clear(); on logout to solve this problem. I could be more precise on this deletion, but it does not matter in this app.


Adding a class to “body” I'm trying to add a custom CSS class to the <body> tag, How can I modify or pre-process the <body> tag to add the class body, Is it right to style the <body> tag with css file?

Alternatively, you could implement template_preprocess_html in your [themename].theme file.

function themename_preprocess_html(&$variables) {
  $variables['attributes']['class'][] = 'class-name';
}

See the documentation: https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template_preprocess_html/8.2.x


How do I make a rule that deletes a node when it hasn't been viewed for "X" amount of time? Im on d7. I what to delete nodes that are no longer "pertinent" on my site. I figure the best way to do tho would be with rules scheduler, but if anyone has any other suggestions, I would be open to them.
Thanks

I am unfamiliar with any current modules that accomplish this. D7's default structure does not store last_accessed or similar statistics outside the watchdog, which would be complex to parse and use.

IMHO accomplishing this goal would involve creating a custom module that :

Adds a field to store a 'last accessed' field linked to your nodes.
Hooks into hook_node_view to update this field each time a node
is viewed
Hooks into hook_cron to conditionally select any nodes with
viewed age greater than your maximum. Call node_delete for each. You could also set $node->status=0 and archive the content without deleting it.

Optionally, you could also add an admin dialog through hook_menu that set a variable defining the maximium unviewed age of nodes.


Login using REST request gives 404 This is so simple login request but cannot figure out why I am getting such error message when trying to login using Postman.

I use url http://localhost:8080/user/login?_format=json and input in the header Content-Type:application/json and I have in my body {"name":"user", "pass":"pass"} but I am getting this error message

  {     "message": "The \"user\" parameter was not converted for the path
  \"/user/{user}\" (route name: \"rest.entity.user.GET\")" }

Using curl works though:

curl --header "Content-type: application/json" --request POST --data '{"name":"admin", "pass":"pass"}' http://localhost:8080/user/login?_format=json

curl result:

  {"current_user":{"uid":"1","roles":["authenticated","administrator"],"name":"admin"},"csrf_token":"XXXXX","logout_token":"XXXXX"}

I have faced the same issue and resolved it by selecting "POST" method from dropdown list.

Find the below image:-

OUTPUT:-
{
    "current_user": {
        "uid": "1",
        "roles": [
            "authenticated",
            "administrator"
        ],
        "name": "admin"
    },
    "csrf_token": "XXXXXXXXXXXX",
    "logout_token": "XXXXXXXXXXX"
}

Note: we can get this output for the first time, if we try for the second time we will get message like

  {
      "message": "This route can only be accessed by anonymous users." }

because postman works as a browser.
To get it work for the second time we need to remove the cookie from postman.

Kindly let me know if I am wrong.
Thanks..


Custom Field For a Content Type I have a field in my content type for blood pressure which, as you may or may not know, is measured ##/###. Currently, I have one text box and I ask the users to enter data in the form ##/### which works well but, on phones the '/' characters is annoying to navigate to. I was wondering how I could split up the field some that it would be 2 input fields separated with a '/' like:

Blood Pressure
[   ] / [   ]

Where [   ] represents a input field.

Any other suggestions to solve this problem would be great as well.

Thanks

Honestly, I'd recommend creating two separate fields, one for systolic pressure and another for diastolic pressure.  Then, use CSS to organize the fields the way you want.  It actually makes more sense to do it this way since they represent two distinct values, even though they're used together conventionally to represent blood pressure.

To expand on the answer, specifically on the CSS side, here are some additional tips.

Once you've found a way to isolate the two fields with classes, I recommend displaying both of their div wrappers as display: inline-block; and, for the first field (systolic pressure) give it a rule that uses the after pseudo-class to add the '/'.

.classes .isolating .systolic-field:after {
  content: "/";
}
.classes .isolating .systolic-field {
  display: inline-block;
}
.classes .isolating .diastolic-field {
  display: inline-block;
}

If you're not familiar with CSS I can provide a more "concrete" example, but this should be sufficient.


Problem with form submit handler using system_settings_form for module admin I have a module which creates an admin backend.  I create the form as below.  The submit handler is called, but for some reason there is no form state.

Any idea what's wrong please?

     //in hook menu
    'page arguments' => array('carousel_form'),

    function carousel_form($form, &$form_state) {
       $form = array();

      /* first fieldset */
      $form['fieldset_1'] = array(
      '#type' => 'fieldset',
      '#title' => t('Carousel slide 1'),
      '#description' => t('Configure the first slide of the carousel here'),
      '#required' => TRUE,
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
       );
       //more fields etc etc

      $form['#submit'][] = 'my_custom_handler';

      return system_settings_form($form);
      }

      //create a handler

      function my_custom_handler($form, &$form_state) {
      $file = file_load($form_state['fieldset_1']['pic_1']);
      //causes error, Undefined index: fieldset_1

      }

Not quite...$form_state is defined (or at least will be if you have a standard installation of Drupal).

The problem is the submitted values are in $form_state['values'], not $form_state. Also, Unless you have #tree set to TRUE on $form['fieldset_1'] the values will be collapsed, and the hierarchy you're expecting won't be there.

This should work:

$file = file_load($form_state['values']['pic_1']);


Insert module inserts image twice? So I'm kind of new to Drupal and I apologise if this is a stupid question. But I've been trying to get both FlexSlider and Insert to display correctly in the frontend. I've add them to the basic content content type.

Both modules have an image field and display associated with them and they do indeed show up in the frontend, but if I use the Insert module then the image gets show twice and I can't get FlexSlider to appear before the content.

The Edit screen displays correctly:

You can see the slider image field is before the body content and title as I've defined in fields and there is only one image upload and an insert button which works as expected.

But then if you look at what is output on the home page:

You can see that (a) the slider is showing at the bottom of the page and (b) the uploading images are displayed unless I delete them after uploading and inserting them.

You just need to go to the "Manage Display" admin page for your content type (e.g. http://mysite.com/admin/structure/types/manage/article/fields for the 'article' content type).

There you can hide/reorder all of the fields in your content type.

I would guess that currently you have a display field that's aggregating the "Image" field inside of it, and that you also have the "Image" field itself set to display. This would account for the same image being displayed twice.


Page render array for front page I need to paste full front page of Drupal site to other page. Can I get page render array for front page for example in html.tpl of not-front page? Thanks!

You can install Devel module and enable "Display $page array" on Devel settings page (/devel/settings).

Or you can implement hook_page_build() to get $page array:

YOURMODULE_page_build(&$page) {
  print_r($page);
}


Getting the apartment cleaning and dish washing to work properly with Omega Theme? I have enabled the setting under themes for the option, "It also helps you to clean your appartment and wash your dishes." Although double and triple checked, there appears to be no change.

I looked through the code to see if there was anything I could fix but unfortunately I'm a little light on my life-theming capabilities. I haven't yet been able to integrate Drupal with reality as of yet.

Am I missing an extra setting or is this a known bug?

check settings for filth and grime under settings.php, these settings override any other setting in omega be sure they are both are set to active. Run update.php.

It's possible that your filth and grime settings are set too low so you may need to adjust these in your ini.php file. (i have mine set to "CDC alert")

Any use of hand-sanitizer or disinfecting sprays can cause the omega settings to malfunction, this is a known issue.


How do I convert a Wordpress theme? I googled, but I didn't find any automated solution. So, I've started it manually. Mapping CSS files is easy, but I'm looking for a way to map blocks/templates. Please, help.

There is no direct way to do it nor any programmatic way. This is because the template structures differ so much. But here are the steps you should take for the fastest conversions...

Load theme in Wordpress then view site in a browser. (the purpose of this is to extract the basic HTML structure of the template).
View source on the page, copy all the HTML and drop into a text editor. Save into a new project folder.
Copy over CSS and JS files to this new project folder. I recommend using a "css" folder and a "js" folder for organization.
Copy over all images to this project folder. I recommend using "images" folder.
Now you have the base template you need to turn it into a theme for Drupal. Time to get busy!
I recommend copying the "garland" theme to a new project folder and renaming it to your new theme name. This will speed things up.
Copy over the css, js, and images folders to the new theme project.
Edit the .info file to load css and js files.
Modify the css and js files to load any images and other file paths to be relative to them.
Using a side-by-side comparison between the page.tpl.php and your template html file you will need to transform the structure of the tpl file to be close to that of the html file. Be careful not to remove dynamic references.
Test, troubleshoot as needed.

Its a lot of steps, but it works. You can also use a theme framework that provides a skeleton theme to build upon. The only problem with this is that sometimes these frameworks are very heavy handed and do far more than is needed. Zen is a common one, but it is very heavy handed. You can find more on the Drupal website at drupal.org (search for themes). Below are some links to a few base themes.

Zen Framework
NineSixty (960 Grid System, very flexible concept, I have never used it though)
Fluid Grid (another great concept, I have seen this in action and its pretty nice)

Finally, here is a link to Drupal's theming guide.


View: Link to content is always rendering in the default language I have a View that is list of a content type using fields. (I am also using a Relationship and a Contextual Filter, btw.)

One of those fields is "link to content".

The content type is translatable. The View is filtered by Translation language (= Interface text language selected for page). In my secondary language (German) only nodes with a translation are shown. So far, so good.

The rendering language is set to: Interface text language selected for page.

However, the rendered rows always link to the default language (/en), even when the rest of the page is rendered in the secondary language (de).

What can I do to get the rows to render the links in the correct language?

It's a bug and it's being worked on, the solution is provided and it's currently labeled as Needs review. Perhaps you can apply the patch and test yourself:

Entity Links fields does not have translation support

In Drupal 8.4 and earlier versions it was possible to use the workaround of Path field and using Custom text field to construct the link:

{% trans %} View more {% endtrans %}

The Path field output correctly translated links with correct path prefix, see here: Translate Content: Link to Content field on Views in Drupal 8. But in Drupal 8.5 the Path field is no longer supported, so you have to patch or wait for the update to gets released.


how to load my css and js first on drupal 7 I'm using Omega theme as base theme and created subtheme. I disabled the "responsive grid" in subtheme.

It works perfectly in screen width 960px as "DEFAULT (960PX) LAYOUT SETTING (Normal)".

When i load the same website in Wide screen more than 1200 px, first it loads "DEFAULT (960PX) LAYOUT SETTING (Normal)" after it override my CSS which i wrote of Wide screen.

How to load my CSS and JS first to make sure the CSS will work for wide screen as well.

My advice is that you enable the responsive grid and then you could apply CSS to the site by using the following basic format. If you read my inline comments, I think you'll get the gist of it.

There is an alternate way to do this where each breakpoint's css is put in its own file. This involves adding some lines to your subtheme's .info file and is pretty well documented here.

This approach may seem overwhelming to you (it did to me at first), but you'll be making a responsive site (one that looks good on all devices) which is a really great skill to have. You test the different breakpoints by resizing your browser window or using browser developer tools. You should also test on actual devices, but I do my initial design and testing by just resizing my window.

/*CSS for genchstyle theme - all breakpoints*/

/*GLOBAL STYLE INFO FOR ALL DISPLAY BREAKPOINTS*/

    h2 {
    color:rgb(204,204,204);
    font-family:Arial,Helvetica,sans-serif;
    font-size:1.2em;
    }

/*MEDIA QUERIES FOR RESPONSIVE DESIGNS*/

/*Wide - larger computer screens and retina devices*/
@media all and (min-width: 1200px) {

    body{
    background:#000 url(../../../../default/files/grate-wide.jpg) repeat;
    background-attachment:fixed;
    width:100%;
    font-size:100%;
    }

}

/*Normal - iPad horizontal & small-to-medium computer screens*/
@media all and (max-width: 1200px) {

    body{
    background:#000 url(../../../../default/files/grate-normal.jpg) repeat;
    background-attachment:fixed;
    width:100%;
    font-size:100%;
    }

}

/*Narrow - iPad vertical & kindle fire, etc.*/
@media all and (max-width: 960px) {

    body{
    background:#000 url(../../../../default/files/grate-narrow.jpg) repeat;
    background-attachment:fixed;
    width:100%;
    font-size:90%;
    }

}

/*Fluid - Small Mobile Devices & smart phones*/
@media all and (max-width: 720px) {

/*Background - mobile*/

    body{
    background:#000 url(../../../../default/files/grate-fluid.jpg) repeat;
    background-attachment:fixed;
    width:100%;
    font-size:90%;
    }

}

You can see this in action on the site I'm building (it's an omega subtheme).

I love Omega and I think you made a really smart choice basing your subtheme on it. But it's the responsive grid that makes it great! Just my opinion.

Oh - and I'm just naming this css file global.css and I'm storing it in my sites/all/themes/mytheme/css directory.


Changing block templates based on context? moving title in body field in template Is it possible to change my block template suggestion based on a particular context?

E.g. On certain parent landing pages (I could manually set; because there are only 3 conditions no determinate pattern), I need the block title to go inside the content <div>.

I could do a workaround and add the title in the body field. Although, I don't want to modify the block content (to add title in the body area/field) because they maybe used on other taxonomy pages; and the clients will have a hard time managing this (calls asking why is the title shown twice in the block management).

Would or could this be best in terms of most efficient solution achieved by preprocessing?

Current output on pages (Default drupal templates in psuedocode):

div.block-block-{delta}
  h2.block-title
  div.content

Desired output (on set parent landing pages)

   div.block-block-{delta}
     div.content
       h2.block-title

Desired output (on all other taxonomy pages)

div.block-block-{delta}
  h2.block-title
  div.content

Update:

These landing pages are just three nodes that the client wants. Theres not really a rhyme or reason to what determines if it is a landing page. I just need to set three node id's to trigger the block template change.

You mention the word 'context' in the first line of your question. Take a look at the Context module. I just came from this page

http://www.metachunk.com/blog/context-based-template-suggestions-drupal-7

Edit: elaborating .. here's the context module
http://drupal.org/project/context
Install it and create a context 'mycontext' for your 3 pages.

Based on this context, provide a template suggestion as mentioned in Topsitemakers' answer. In your themes template.php, it should be something like (not tested)

mytheme_preprocess_block($&vars) {
  $context = context_get();
  if(isset($context['context']['mycontext'])) {
    $vars['theme_hook_suggestions'][] = "block__mycontext";
  }
}

You can do this more generic as described in the post linked above. Now, your block will render using block--mycontext.tpl.php, if it exists, when shown in the 'mycontext' context.

$2c,
*-pike


Hide Fields in Edit Page based on Role and Content Type? Use Case: Content Editor A (Role of Monday)  when edting a node (of Content Type Alpha) is able to use Field AA and Field BB.

But Content Editor B (Role of Tuesday), when editing the same node, does not see Field AA and Field BB.

I have experimented with many of the modules of this regard (Field Permissions, Conditional Fields, Rules), but nothing that can compute for  all four conditions (role, content type, edit, fields).

How does field permissions, custom permissions, not work for you?

  Example: Using field permisions, I am able to "hide" Field AA by not allowing Content Editor A (Role of Monday) to Edit, or View. But...it also hides the Field AA in Views. That's not what I want. The Editor should still be able to see the Field in any View.

In the above picture, Monday is not going to see the field when he edits the page, but will be able to see the field when its displayed by views.

This is the solution to the Example you provided. In your original question, it would be the role of Tuesday who needs to look like that.


Using Panels to display Taxonomy terms My Drupal 6 taxonomy terms are linked to two types of content, one is called Results (text) the other is a Photo.  Is it possible through Panels to develop a node where a user can select a term via a drop down menu then it will display only the Results and the pictures related to that term?  My goal is to have all of the results together in their own region and the same with the photo.

If it can be done, is there a recommended recipe I should follow?

If it can't be done any suggestion on how to do it?

Drupal Panels can do this using the Views module. The two modules work very well together to arrange your content on a page, but Views is the workhorse for sorting through the content and selecting what you want.  Check out the video series "Taming the Beast" at Nodeone.se for how to use Views.  They also have a series on Panels/Page Manger that shows how to link them.


Drupal multisite and alias suffix I am actualy working on drupal multisite environment and I am stuck within a alias suffix problem.

I made a setup like this in my sites.php file for the multisite alias names.

$sites['example.example.de'] = 'example.example.de';
$sites['tp-ref.example.example.de.vwp'] = 'example.example.de';
$sites['tp-tst.example.example.de.vwp'] = 'example.example.de';
$sites['tp-dev.example.example.de.vwp'] = 'example.example.de';
$sites['tp-local.example.example.de.vwp'] = 'example.example.de';

My VHost Config file is the following.

<VirtualHost *:80>
  DocumentRoot "C:/seu/xampp/htdocs/iptp"
  ServerName example.example.de
  ServerAlias tp-ref.example.example.de/vwp tp-tst.example.example.de/vwp tp-dev.example.example.de/vwp tp-local.example.example.de/vwp
</VirtualHost>

The host file contains the following lines.

127.0.0.1 example.example.de
127.0.0.1 tp-ref.example.example.de
127.0.0.1 tp-tst.example.example.de
127.0.0.1 tp-dev.example.example.de
127.0.0.1 tp-local.example.example.de

The URL example.example.de works without any problems; when I am trying to open one of the other URLs, I could open the page, but Drupal seems to have a problem with the path.
For example, if I want to open the URL "tp-ref.example.example.de/vwp", Drupal trys to load all CSS and JavaScript files from tp-ref.example.example.de, but it should load it from tp-ref.example.example.de/vwp.

I think this is a base path problem. Does Anyone have an idea about how fix this?

The comment shown in the sites.php is the following one. I used it to edit the sites.php file.

/*
 * URL: http://dev.drupal.org
 * $sites['dev.drupal.org'] = 'example.com';
 *
 * URL: http://localhost/example
 * $sites['localhost.example'] = 'example.com';
 *
 * URL: http://localhost:8080/example
 * $sites['8080.localhost.example'] = 'example.com';
 *
 * URL: http://www.drupal.org:8080/mysite/test/
 * $sites['8080.www.drupal.org.mysite.test'] = 'example.com';
 */

As you're loading all these sites from one directory: 'example.example.de'. You only have one site and therefore one settings.php file and ONE base path which defaults to the root domain.

To do what you'd like to do you'd actually need to multisite these with separate directories for each site. To the best of my knowledge anyway.


How do I change a core error message? I would like to change the default error message from Drupal core.

The error message is "Please Select the Valid File Format".

My problem is in brief below.

I have created a CCK called 'Assignment'.
There I have given the users an option to upload files.
In such case if the user uploads invalid file format drupal will throw the error message as mentioned above.
I need to change the error message in to "The file upload field cannot upload the speicified filed".

How can I achieve this?

(Should not use string overrides module)

Thanks in advance..

If that string is run through the t() function (which is probably is) and you don't want to use  String Overrides, then you can update your settings file.

For Drupal 6, putting this in your "settings.php" file should work.

$conf["locale_custom_strings_en"] = array(
  "Please Select the Valid File Format" => "The file upload field cannot upload the speicified filed",
);

In Drupal 7, you would change it to

$conf["locale_custom_strings_en"][""] = array(
  "Please Select the Valid File Format" => "The file upload field cannot upload the speicified filed",
);

However, I am not seeing the string "Please Select the Valid File Format" in any of my D6 installs, and that is not the message I get when try to upload to a CCK filefield with the wrong file type or the MIME type doesn't match the file extension.


Disable drag and drop/ Show row weights The drag and drop screws up my theme when viewing it on a mobile device. Since this feature isn't necessary for my site can i completely remove these options to my users? I want to remove all drag and drop functionality.

Im using corolla Corolla 7.x-3.0-rc1.

This can be duplicated by viewing my site and dragging the window to be the smallest width. The drag and drop table does not adjust its width.

You'll want to alter settings.tableDrag to remove that drag and drop functionality, but I think what you're actually running into is a css rule that sets a width for the table.


How to tell if a site is using Drupal 7 I know how to check if a site is built with Drupal, but is there a way to tell if a site is built with Drupal 7?

Some obvious giveaways to the site being drupal 7:

RDF in the <head> section in the HTML
Meta tag of <meta name="Generator" content="Drupal 7 (http://drupal.org)" />
Executing jQuery.fn.jquery; reveals the jQuery version to be 1.4.4 or 1.5.2 (with jQuery update)
Only a single <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> - this is a famous drupal 6 bug (it has two in the <head> section
HTTP response header of X-Generator: Drupal 7 (http://drupal.org)

Other options include using 'sniffers', my favourite being 'Whatweb' - https://github.com/urbanadventurer/WhatWeb. Whatweb is a (ruby) command line tool that can sniff not only the fact that the site is using drupal, but often the major and minor version as well


Adding an email field to comment forms I have given permission for anonymous users to comment on my site. But the default comment form being displayed does not have a field for email address in it. Also, I have comment notify installed. The email field to be displayed on the comment field should be recognized by comment notify as the email address of the commentor so that it can send notifications. Also, the email field should not be made visible for logged in users. I cannot solve all the three problems at once. Any help will be greatly appreciated.

I think you can make this work as follows:

In the Permissions settings via admin/people/permissions, ensure ANONYMOUS USER can View comments, Post comments, and Subscribe to comment notifications
In the Comment Notify settings via admin/config/people/comment_notify, ensure comment notification is enabled for the content type(s) you care about
For each content type you care about, e.g. for Basic page via admin/structure/types/manage/page, expand the Comment settings tab in the vertical menu at the bottom of the page and ensure "Anonymous commenting" is set to Anonymous posters must leave their contact information


Get the values of views fields in a Twig template I have created a view that outputs 3 fields for each row. Just using views, i can get the output to look something like this:

<li>[Field1 Value] [field2 value] [field3 value]</li>

I have a requirement to set a data-attribute on the list items to on of the field values. Also, I want to wrap an anchor linking to the detail view of the content around all three field values.

I've tried using a twig template like views-view-fields.html.twig (too generic i know, but for testing purposes) but the values dont seem to be there. I can do {{ dump (fields|keys) }} and i see my fields there, but if i do {{ dump (fields.my_field|keys) }} then its just an empty array.

I also tried using a template like page--[name of my page created by views].html.twig but couldn't seem to find the values for those fields there either.

Any help on advice as to where I should be looking, particulary which twig templates I might create/override and how to get the values would be very much appreciated!

In the template file (views-view-field), you can use

 {{ row._entity.field_name1.value }} {{ row._entity.field_name2.value }} {{ row._entity.field_name3.value }}

Or, in your theme, in the preprocess function you can overwrite the output:

function your_theme_name_preprocess_views_view_field(&$variables) {
    $view = $variables['view'];
    if ($view->storage->id() == 'your_view_name') {
        $variables['output'] = '
' .
          $variables['row']->_entity->field_name1->value .
          $variables['row']->_entity->field_name2->value .
          $variables['row']->_entity->field_name3->value .
        '
';
    }
}


db_query() function in a foreach cycle - only the first query is getting executed (D6) I have a query, which I have to run in a foreach cycle.
I run the query with db_query() function.
My code looks similar to this one (of course, this is just an example code with example values):

$query = '
    UPDATE mytable SET some_fields = "%s"
    WHERE
    some_fields = "%s"AND
    other_field = "%s" AND
    another_field = "%s"
    ';

foreach($blabla as $index => $value){
    $prev_value = 'these variables are set in the meantime too...';
    $other_field_value = 'blabla';
    $another_field_value = 'blablabla';

    if($this_is_my_condition){
        $query_result = db_query( $query,
            $value,
            $prev_value,
            $other_field_value,
            $another_field_value
        );

        $affected_rows = db_affected_rows();

        if( empty($query_result) or empty($affected_rows) ){
            $unsuccessful_queries[] = 'blablabla '.$index.', '.$value;
        }
    }
}

if(!empty($unsuccessful_queries)){
    $errorMsg = NULL;
    foreach($unsuccessful_queries as $index => $value){
        $errorMsg .= 'Setting '.$value.' parameter was unsuccessful!<br />'."\n";
    }
    throw new ParameterSettingException($errorMsg);
}

In theory, my query is OK, because it works for just one query perfectly with the same values (if it has to be run depending on my condition ( in the example above, $this_is_my_condition ) ), BUT it doesn't work for multiple queries, the rest of the queries are getting simply ignored: my $unsuccessful_queries array is full of the other to-be-updated stuffs that would have to be executed.
The values are correct (that's for sure, because these work with the same values, but with just ONE query!!).

What can be the source of the problem? Why can I run only ONE query, why are the others getting ignored?

Thanks in advance!

I'm not sure if checking the return of $query_result against empty() is meaningful, since the only indication query failed is if it returns FALSE. Same for $affected_rows, since the query may be successful but not necessary change any rows.

I'd suggest installing Devel module because it has a feature which records and prints all DB queries on a page load. This would enable you to see the actual query(ies).


Views: Showing related nodes from the tagged taxonomy term using views I have two content types, Article and FAQ. They both have a Term reference field for tagging from the same taxonomy vocabulary called subject.

So on Article node view page, I want to display the three latest FAQ nodes that are tagged the same taxonomy term as to the currently displayed Article node, using views.

Please give me some idea. Thanks

Create view (block)
Add fields (title)
Add Contextual filters: "Content: Has taxonomy term ID"
Configuration on this filter:

When the filter value is NOT in the URL
Provide default value
Type: Taxonomy Term ID from URL. Under that, check the box "Load default filter from node page, that's good for related taxonomy blocks." Check the boxes of the taxonomies you want involved here

Filter criteria: Content: Type (= FAQ)


how to filter blog posts by taxonomy and by year I have been trying to build a filter fuctionality for blog posts. I would want to filter by taxonomy terms and by the year the post was published. So basically in the content I want to list all blog posts – on sidebar I would have all used taxonomy terms listed and also a list of all years/months when post have been published.

Additionally I want the filter to be reflected by the URL structure:

For a URL like  domain.com/blog/2014 all posts from 2014 would be listed.
For a URL like domain.com/blog/cars only posts tagged with 'car' would be listed.

Is there a module to do this – or should this be done with views? I have been trying to do this with views now but with not much luck. Especially with the url I don't understand how i can do that. Or if there is some tutorials on somewhere – that would help also.

You're on the right track. Views is good way to solve this with Contextual Filters. You need to create a page view with the path blog. That will create a page example.com/blog that shows all blog posts.

Adding a Content: Created year contextual filter will set up a filter rule so that example.com/blog/XXXX filter the view by posts created on year XXXX.

For your last need, tag filtering, you're going to need to add another page view since a page view can't do a mixed contextual filtering; views doesn't know how to treat XXXX in example.com/blog/XXXX as both a year or tag.

See this post on how to set up a filter Content: Has taxonomy term ID filter that will you create something like example.com/tags/YYYY where YYYY is the name of your tag.