Drupal 7 url with hex code for special characters? The URLs for a Drupal 7 site are like the following ones:

http://example.com/drupal7/?q=node/1#overlay=%3Fq%3Dnode%252Fadd%252Farticle
http://example.com/drupal7/?q=node/1#overlay=%3Fq%3Dadmin%252Fconfig%252Fcontent%252Fformats

I am into module development and this is quite irritating. How do I display the special characters, the "slashes/", "#", "&" symbols that have been converted to hexadecimal codes?

You can use the following snippet.

$decoded_url = rawurldecode(rawurldecode($url));

For example, for the second URL, the code returns http://example.com/drupal7/?q=node/1#overlay=?q=admin/config/content/formats.

That URL anyway is not usable as it is, as it would be wrongly parsed. For example, if on my browser I enter http://tero.local/dr72/?q=node/1#overlay=?q=admin/config/content/formats (tero.local is the local name used from my computer), what I get is the following page.

As you see, the overlay is not shown.
Differently, when I enter http://tero.local/dr72/?q=node/1#overlay=%3Fq%3Dadmin%252Fconfig%252Fcontent%252Fformats, I get the following.

In this case, the overlay is rendered.


how to show a view with one to many relations I am using Entity Reference, what would be the best way to show the parent entity on the top (4 columns ) and then the children entities in horizontal rows below?
Can Display suite be used?

Yes, Display Suite would work for this. With the right modules and configuration, you may not even need to create a View.


Processing forms together for a tree of related entities I have EntityA which has one or more EntityB's which have one or more EntityC's. EntityB references values of EntityA and EntityC references values of EntityB. My current plan is to have an id field of EntityB reference the id of EntityA and the same for EntityC referencing EntityB. Normal one-to-many relationships, possibly with foreign keys defined so mysql will enforce referential integrity.

I am trying to use the Subform module to build the lists of required forms inside the edit form for EntityA. EntityA builds the settings for a new EntityB into an object and passes that to EntityB's form via Subform '#subform_arguments'.

My question is about how to save EntityB and EntityC forms. Should I save EntityB in the submit function for EntityA or try to communicate EntityA's id to the EntityB submit function and have it save its own entity? If the save logic for EntityB goes in the submit function for EntityA's form, how do I retrieve the subform values to save?

This is working now with entity saving logic neatly packaged with the sub-item entity code. Before saving the subitems, I set the value of a hidden element with the parent entity's id. I modified the wrapper form's submit handler array:

    '#submit' => array(
        'wrapper_form_submit',
        'update_subforms_before_save',
        'subform_submit_all',
    ),

First, the wrapper is saved and is assigned an id. Then it updates the subforms with that id. And finally the subforms are submitted. The function to update the subforms is modeled after subform_submit_all():

function update_subforms_before_save(&$form, &$form_state) {

    $wrapper_item_id = $form_state['values']['item_id'];

    if (!empty($form_state['temporary']['subform'])) {
        foreach ($form_state['temporary']['subform'] as $subform_name => &$subform_state) {

            $subform_element = &subform_array_get_nested_value($form, $subform_state['subform_element_parents'], $subform_exists);
            if ($subform_exists) {

                switch($subform_element['#subform_id']) {
                    case 'subitem_entity_form' :
                        $subform_state['values']['parent_item_id'] = $wrapper_item_id;
                        break;
                }

            }
        }
    }
}


How to resolve the error about 'A partially-completed form was found'? Yesterday I have updated Webform module from 7.x-4.0-beta3 to 7.x-4.13.

After doing so, I am getting this notification message, throughout the site:

  A partially-completed form was found. Please complete the remaining portions

I have also checked some threads.

When I check log entries I got this error :

  Notice: Undefined property: stdClass::$is_draft in webform_client_form()

And deleting partially filled nid in webform submissions table is not working for me.

What can I do with it?

Since "deleting partially filled nid in webform submissions table" (as in your question) seems to not solve your issue, you may want to have a look at comment nr 2 in issue 2560907, which states:

  A webform node is being displayed on that page and there is a draft submission for the current user. You don't have to find the id -- the form will be displayed, unless theming or another module is preventing it.


How to discard unsaved changes to a view when editing it leads to a WSOD? This is one of those times when I tried to add something and realized that I've got it applied to all displays. This time it was a vocabulary filter, so I clicked cancel and it didn't register so I clicked back to site.

After that I tried to edit and it returned

  The website encountered an unexpected error. Please try again later.

The log shows this:

  Exception: No entity type for field vid on view VIEW in
  Drupal\views\Plugin\views\HandlerBase->getEntityType() (line 712 of
  /PATH/core/modules/views/src/Plugin/views/HandlerBase.php).

I checked the active config and couldn't find anything with a vid. Clearing cache and reimporting the view config didn't fix it. So, is there a way?

A quick fix would be to delete the data from the expirable key/value store:

\Drupal::keyValueExpirable('tempstore.shared.views')
  ->delete('view_id');

Alternatively you could wait a week until it expires itself - probably not practical :)


Remote Drush Commands Not Found I'm using a new host for my website and I requested drush access to my site. They said it's all set and told me to run drush commands as such $ ../drush/drush command

I test it out with $ ../drush/drush status and everything works as it should.

The problem comes when I try to run drush commands remotely via my alias file. Everytime time I drush @remote I get drush: not found

I even set path-aliases to point specifically at %drush and %drush-script.

Is there something I'm missing?

If you use, '%path-aliases', either specify the full path to Drush, or ensure that the Drush that you are calling (e.g. drush) is on your PATH.

Example:

$aliases["mysite"] = array (
  'uri' => 'mysite.org',
  'root' => '/path/to/drupalroot',
  'remote-host' => 'myisp.com',
  'remote-user' => 'www-admin',
  'path-aliases' =>
  array (
    '%drush-script' => '/home/myuser/drush/drush',
  ),
);

If setting the PATH in your .bashrc, always do so at the very top of the file.  It is common for boilerplate (host-provided) .bashrc files to have a line somewhere in the middle that exits prematurely when not in interactive mode -- and Drush makes remote Drush calls non-interactively in most instances.


Using a View's exposed Sort Criteria redirects to home page I'm using the Content: Title Sort Criteria as part of a View and I've exposed that so that site visitors can sort results.

However, when (on the front end) I hit the Sort Criteria's "Apply" button I get redirected to the home page.

The URL does retain the sort critieria information, eg: mysite.com/?sort_by=changed&sort_order=ASC

It's just is missing the rest of the URL - the page name. It should be mysite.com/listing-page?sort_by=changed&sort_order=ASC.

Looking at the filter form's action attribute, I see it is set to action="/".

Would anyone know how to fix this?

if you use panels, and i think you are, use content panes only, not block views, etc. and make sure in views UI in middle column to set "use panel path" to yes.


How to embed webform to update existing submission I'm trying to display a webform through a module controller. The webform display works as it should but I need to update existing submission data and instead of updating the existing submission a new one gets created.

The code I use looks like this:

public function edit()
{
  $submissionId = \Drupal::request()->get('sid');
  $webform = Webform::load('eventsignup');
  $webformSubmission = WebformSubmission::load($submissionId);
  $webform = $webform->getSubmissionForm([
    'data' => $webformSubmission->getData()
  ]);

  $build['submissionForm'] = $webform;

  return $build;
}

I tried to alter it by giving the operation "edit" and setting the "sid" but that leads to a duplicate key error:

public function edit()
{
  $submissionId = \Drupal::request()->get('sid');

  $webform = Webform::load('eventsignup');
  $webformSubmission = WebformSubmission::load($submissionId);
  $webform = $webform->getSubmissionForm([
    'sid' => $submissionId,
    'data' => $webformSubmission->getData()
  ], 'edit');

  $build['submissionForm'] = $webform;

  return $build;
}

What am I doing wrong?

Thanks for your help!

Existing webform submissions are entities and you can use the entity form builder service to build the form:

// load the webform submission entity
$webformSubmission = WebformSubmission::load($submissionId);
// build a form for the entity
$webform = \Drupal::service('entity.form_builder')->getForm($webformSubmission, 'edit');


After deleting all nodes, how do I reset the node ID to start from 1 again? I generated tons of dummy content for testing, and then deleted them all.
As nid is auto-increment, newly created node will have a nid of last created nid +1.

How can I make nid start from 1 again?

ALTER TABLE `node` AUTO_INCREMENT = 1;

P.S - Others who have replied on this question: I just did a small check after deleting content and the associated content is indeed deleted, node_revisions and field_* tables are empty. node_delete says the same - http://api.drupal.org/api/drupal/modules--node--node.module/function/node_delete_multiple/7

Sometimes on migrations projects when you migrate from other platforms (ex. ASP + MSSQL), sometimes it becomes unavoidable to reset the nid due to lot of factors. I am sure it could be avoided but time/code tradeoff is always there.


Which module should I use to visualize my Google Analytics Data using the Google Charts engine? I would like to import Google Analytics data of my site into my site, so that I can visualize them with the (interactive) Google Charts API.

Which module(s) should I use for this?

Seems to me that Google Analytics Reports is the solution for this, no? Those "reports" do include charts also (not just tabular data).

If you rather want to create some charts yourself, consider the Comparison of Charting Modules as a possible place to do start from, to find the module that best fits your needs. Possible alternatives that might work for this specific question are the Chart module, or the Charts module, though there are other alternatives in that comparison that might be a better fit for this case.

The license that comes with the related charting library (engine) in each of these modules, should be considered also. It is one of the (important?) selection criteria for deciding on the module to go for. 'Possible privacy concerns' or 'Yes or no support for saving charts in PDFs' is another typical item to consider.

Disclosure: I'm the author of the comparison and modules Chart and Charts, I hope this does not violate the site's policy on self-promotion.


What files will Drupal poll for hooks by default? I tried implementing hook_menu() in an foo.admin.inc file for reasons that aren't important, and discovered that hooks are not checked in said file. However, in the past, I have seen include files with hooks defined in them (e.g. rules.inc), so I was wondering what the default core rule is for this, and how one can specify files outside of the defaults. Does extending where hooks can be checked have a nice Drupal way of doing this, or have module developers used PHP to achieve this end?

An include file will be scanned if the hook is within a group. For example, the rules module defines a group called 'rules' and so Drupal will scan the file foo.rules.inc for implementations of rules hooks.

The hook where groups are defined is hook_hook_info.
See: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_hook_info/7

Also, look at the function module_implements that finds modules implementing a hook: https://api.drupal.org/api/drupal/includes!module.inc/function/module_implements/7


Webform AJAX submission, same problem with multiple approaches I'm trying to set up a Webform with AJAX submission. I've tried 3 approaches in order to complete it, all 3 resulted in the same problem.

I've tried the Webform AJAX module, I've tried a code from this answer and I've tried another module that is in sandbox only in Drupal.org but it supposed work just fine.

Some of these approaches worked on other Drupal projects on mine but not on the current one.

After clicking on the Submit button, the little AJAX loading gif shows up and then the gif remains there but the submission never finishes, the form doesn't get submitted. Exactly the same problem for all approaches.

This is a JS error I'm getting in console

Uncaught TypeError: Object function ( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context, rootjQuery );
    } has no method 'handleError' jquery.form.js?v=2.52:12
s jquery.form.js?v=2.52:12
window.(anonymous function) jquery.form.js?v=2.52:12
onload

Do you have any idea what could possibly cause a bug like this in Drupal 7 with AJAX webform submission?

I've solved the problem with using jquery.form plugin and submit the form via AJAX with the help of this plugin.

I've found this solution in this answer

https://drupal.stackexchange.com/a/23650/9297


How can I output debug info from hook_node_presave()? I'm learning about module design for Drupal 7 and I want to see what hook_node_presave is being passed (and working with), how can I output debug info so that I can learn how to manipulate it?

Is there a similar hook that I can use to print out debug info?

install the devel module and dump your variables with dpm($input, $name = NULL) to the screen.

This article shows additional debugging options.


Drupal 6 Module Storing configuration setting in file I have built a module that uses encryption and I need to store the encryption key somewhere so that it is configurable.

I would like to put it in a file (the equivalent of web.config of .NET website) so that it can be altered but is safe.

Assuming the web server will take care of restricting access to the file, where should I put this file? Is there an existing file for adding configurable settings to per module or even per website (and how can I read these)? Do I have to do something on module install, or in the module info file?

Any help would be appreciated.

The Question was not so clear to me but I can suggest you 2 things.

You can use variable_set('salt', 'unique_hash'); in the .install file in hook_install(). Then this variable will be stored in the variables table. In hook_uninstall() you add variable_del('salt'); So this will remove the variable from the table if the module is uninstalled. You can access it via variable_get('salt', 'default_value'); Also if you want to change it then make a form text field and in the hook_submit for that form make a variable_set('salt', 'edited_value') call. This will update the variable in the variables table. Use user_access() to restrict all users to access it.
The second is, to make a text file in the server file system and make it's permission as 644. Then read the file by php's fread() function and access the file value.


How do I list all core templates? Is there a way to list or get all the Drupal 8 core templates which are being used by a site? The list should exclude the templates coming from the theme.

The method I am using is enabling Twig debugging in the services.yml and checking whether a template is from core using a browser's inspector, but this is tedious.

I don't see a way to get a list of all core templates, but if you want to override them here is a perfect guide, Drupal core template naming


Migrate module. Users from D6 to D7 with preserved UIDs I'm trying to migrate a Drupal 6 site to a totally new implementation of Drupal 7.

I'm using the migrate module, and I am able to successfully migrate users and passwords, as well as their roles, but the users UIDs is not being maintained.

I believe that the issue is that UIDs must be explicitly set on the user object before saving it, and migrate is not doing that for me.

http://drupal.org/node/712966

Any tips on how I can do that? I need my UIDs on Drupal 7 to be exactly the same as Drupal 6!

For migrating to Drupal 7, it's much simpler:

// Pass the old uid through
$this->addFieldMapping('uid', 'uid');
// Tell user_save to create a new account with the given uid (otherwise it sees the
// uid and assumes you're updating an account).
$this->addFieldMapping('is_new')
     ->defaultvalue(1);


title_callback not working for certain user in hook_menu I am developing a module to manage Human Ressources.
I implement hook_menu with a title_callback like this:

$items['intranet/hr/%user'] = array(
  'title callback' => 'user_page_title',
  'title arguments' => array(2),
  'page callback' => '_hr_redirect_to_personal_data',
  'page arguments' => array(2),
  'access callback' => 'hr_check_menu_access',
  'access arguments' => array(2),
  'type' => MENU_NORMAL_ITEM,
  'menu_name' => 'navigation',
);

Users with certain role and the user to whom the HR data belongs can access to this menu, and should see the name of the concerned user.
It works perfectly if the logged user has a role, but the title of the menu is "Home" for the user to whom the HR data belongs.
I don't understand what's happening as I am implementing hook_menu() the same way the user module does for the user profile page.
If I inspect the menu with the devel menu, the title is correct for every user.
Any idea on what I am doing wrong ?
Thanks!

I get it !

In my configuration, the path intranet/hr is a view which is not accessible to every user, that's why the children element is not accessible and I have "Home" as the menu title.

Even if I don't know how to change this behaviour, at least I know why it is happening :-)


Unknown User Registered into my system I'm currently doing recruitment system by using drupal 7.. In my system, the user (anonymous) need to register before they can log in into the system. For log in and registration, i use LoginToboggan module. i also use the captcha module to avoid from spam.
However, when i look at the people..there is a lot of unknown user.. and it seems like spam.
what should i do?

These are robot spam registrations. To my eye, they look like they originate from XRumer.  XRumer knows how to complete the registration process of LoginToboggan and knows how to solve simple CAPTCHAs, so these measures will not stop XRumer from registering.

The modules I've found to be most effective against robot spam registrations are MotherMayI and CAPTCHA Riddler.

Both these are based upon the same idea: To register, the registrant should be able to answer a simple question where the answer is obvious to a human, but not to a robot.

If you site's language is not English, almost any question will work, since robots do not have multi-language skills.

CAPTCHA Riddler lets you set up a "pool" of questions (so a returning robot will face a different question on each visit).  MotherMayI only allows one question, but let you set up an RegExp for the answer and also has allows for a longer text to "hint" to a human what is expected.  I currently prefer MotherMayI, but check out both.

PS: So far, no spam robot has managed to register at any of my 20 sites (all that accepts registrations by the public are protected by MotherMayI).


How can I create a new content by adding another two contents of same content type? How can I create a new content by adding another two contents of same content type?
My situation is
I have one content type 'Student'
and in another content type 'Receipts' whi has one field called months (list field) which stores the fee paid for each term (eg. April, May, June).
the student pays fee for term wise, for term2 fee another Receipt content is created...

Then I acreated a view (Student + Receipts),
It displays like

No Name           Class           Paid Months
1  Sravan         10 A            Apr, May, June
2  Sravan         10 A            Sep, Oct, Nov, Dec
3  Manohar        9 B             Sep, Oct, Nov, Dec (Joined only on Sep)
4  Sreeram        8 C             (No Fee Paid Yet)

I want to find those who did not paid the fee for Apr, May, June..

but when I displayed it shows 'Sravan' in the list cause it searches in his 2nd Receipt for Sep, Oct, Nov, Dec.  (Apr is not in that list)

How can I solve this..

Sorry for my lengthy question.. I would like to explain my situation in details...

Entity Reference Module should be used for such cases

To use the entity reference field in views you should follow the link given below
https://www.youtube.com/watch?v=4Pdii7aFIvc
http://codekarate.com/daily-dose-of-drupal/using-views-entity-reference-module-drupal-7

In the advanced section of views you have a relationship option where you will get an option to use a referenced entity for the view of content type A(student).


Breadcrumbs Not Displaying Properly I am experiencing problems with breadcrumb trails inconsistently not displaying correctly. I am using the core breadcrumb module, without any others installed. (I did have Custom Breadcrumbs installed but have since uninstalled and removed it.)

I have links to nodes nested in parent items in the main menu like this:
Home > Chapter > Topic > Subtopic.
Most nodes are displaying the breadcrumbs like that, which is what I want. However, a few are displaying like this:
Home > Subtopic (not showing the chapter and topic under which they are listed)

I believe I started getting this error when I changed the numerical weight of the menu items in structure > menu. I have since changed their depth, changed their parent menu item, flushed caches, nothing has worked. It is only a few nodes with the problem and they were originally working as expected. I cannot recreate this problem either. If I create new nodes they show the proper breadcrumb trail. The items in question are all as they should be in weight and parent menu item position they should be. If I install Custom Breadcrumbs I can force the breadcrumb trail to the desired state. Is there a table that I can flush in the database that will fix this problem? Is there a way to fix this without deleting the node and recreating it?

Edit: I found the problem. I have links to these nodes in two different menus on the same page. Drupal is using the other menu I created instead of the Main-Menu to make the breadcrumb trail.

It looks you need to fix the breadcrumbs for a particular contentHere is my idea.

  In your theme, in template.php implement theme_breadcrumns(), as below
  Inside the theme_breadcrumbs() implementation check type of node using

menu_get_object()

function YOURTHEMENAME_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];

// Lets assume your content type name is chapter
  $node = menu_get_object();
  $node_type = $node->type;
  if($store == "chapter") {
     $links[0] =  l(t('Home'), '<front>');
     $links[1] =  t('Chapter');
     $links[2] =  t('Topic');
     $links[3] =  t($node->title); // Considering Sub topic as node title
     drupal_set_breadcrumb($links);
  }


Change site logo for specific content type and page How to add different logo images for specific content type and page. It want to be dynamic.When user add content, user want to select logo

Do not know weather this method fulfill the requirements but you can take a look. As Drupal 8 creates a block for logo. You can create separate block for each content type and depends on visibility condition you can show.


Custom Views Sort Order Using Filter Value I have a View containing a list of events.  There is a date field on the event content type which contains start and end time:

There is a filter for start time, which is setup using the Views Between Dates Filter:

This means that entering 11:00am in the filter will ensure that the event with time 10:00 AM to 3:00PM exists in the results since 11 falls between 10 and 3.

The full result set might look like the following when using 11am for the filter:

7am to 3pm
8am to 12pm
9am to 11:30pm
11am to 12:00pm
11am to 1pm

How can I create a custom sort, such that the exact matches for start time are ordered first?  These are the results I need:

11am to 12:00pm
11am to 1pm
7am to 3pm
8am to 12pm
9am to 11:30pm

Is there a way to create a custom sort handler for views using filter values?

EDIT: I'd hoped I could use hook_views_post_execute to re-order the data but I'm using a pager, so only the first 10 results exist in $view->result

In the end, my client agreed this feature was overkill and it was ommitted but I thought of a way it could be achieved.

Potential Solution

The following is only feasible if you have a finite and relatively low number of filter values because you need to create a field for every filter value.

Create a field of type boolean for every filter value.  In our case we had 10, 11, 12, 1, 2, 3 as potential values for hour and 00, 15, 30, 45 for minute.  24 possible combinations, so 24 fields need added to the event type.
The field should be named according to the filter combination, e.g. Sort: 10:00, Sort: 10:15 etc.
The field value should be set as either 1 or 0.  If the event start time matches the time in the name of sort field then this should be set to 1 otherwise it should be set to 0.  hook_node_insert and hook_node_update could be used to set the values.

E.g on each event you would have:

Start Time - 11:00

Sort 10:00 - 0
Sort 10:15 - 0
Sort 10:30 - 0
Sort 10:45 - 0
Sort 11:00 - 1
etc (the rest would be set to 0).

When the filter is applied, use hook_views_query_alter to grab the filter value.  Then set the sort based on that field.

E.g if the user entered 11:00 as the filter value, we could force the sort to use the Sort: 11:00 field.  The following is written off the top of my head, so would need some tweaks:

function my_module_views_query_alter(&$view, &$query) {
  if($view->exposed_input['field_start_time'][0]['value'] == "11:00am") {
    $view->query->orderby[0]['field'] = "field_data_field_sort_11_00_value";
    $view->query->orderby[0]['direction'] = "DESC";
    // Add any secondary sorts.
  }
  else if($view->exposed_input['field_start_time'][0]['value'] == "11:15am") {
    $view->query->orderby[0]['field'] = "field_data_field_sort_11_15_value";
    $view->query->orderby[0]['direction'] = "DESC";
    // Add any secondary sorts.
  }
}


Get the form ID from a Webform entity I need to output the form id of a webform entity.
I load a chunk of enabled webforms directly from the database by using

\Drupal::entityTypeManager()->getStorage('webform')->loadMultiple();

Afterwards I have to output the form_id's of the webform entities.

How to achieve this? I cannot see any "form_id" stored in the returned entity object.

UPDATE:

I can use the following script to receive a static version of the form id:

$target_form_id = str_replace('email_confirm_redirect_2_', '', $entity->getSubmissionForm()['#form_id']);

Still not really professional

Rather than storing the form ID, you could just store the webform ID and check that in a form alter. Webform provides its own form alter hook that only fires for webforms and lets you put the hook in a dedicated include file.

See honeypot_webform_submission_form_alter() in third_party_settings/webform.honeypot.inc for an example of getting the webform from the hook:

/**
 * Implements hook_webform_submission_form_alter().
 */
function honeypot_webform_submission_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // <snip>

  /** @var \Drupal\webform\WebformSubmissionInterface $webform_submission */
  $webform_submission = $form_state->getFormObject()->getEntity();
  $webform = $webform_submission->getWebform();

From there you can use $webform->id() to get the webform ID.


Show Active terms from vocabulary using taxonomy menu What i want: Active terms of vocabulary in main menu.

What i have done so far:

I have used taxonomy_menu module.
Created taxonomy(Category).
Added "Status" field having boolean values (0 = Inactive, 1 = Active).
Added two terms in Category(Cat1 and Cat2).
Cat1 = Active, Cat2 = Inactive.
Configured menu from "Edit vocabulary" section.

Problem: All terms of vocabulary are included in main menu. I want that only those terms whose Status = Active should be displayed in main menu.

Community, please help. Any hint would be helpful.

You can do this by using hook on taxonomy insert and update inside a custom module.

Here is a sample of code (needs refactoring/cleaning/checking but that's a start and it works for me) :

function custom_module_taxonomy_menu_insert(&$item) {
  //load taxonomy to access fields
  $tax = taxonomy_term_load($item['tid']);
  //get your field display (here i called it field_status)
  $display = isset($tax->field_status['und'][0]['value'])?$tax->field_status['und'][0]['value']:'';
  //check your value
  if($display == 0) {
    //I don't want to display this element
    $item['remove'] = TRUE;
    return $item;
  }
}

function custom_module_taxonomy_menu_update(&$item) {
  //IDEM without comments
  $tax = taxonomy_term_load($item['tid']);
  $display = isset($tax->field_status['und'][0]['value'])?$tax->field_status['und'][0]['value']:'';
  if($display == 0) {
    $item['remove'] = TRUE;
    return $item;
  }
}

[Edit to add some details]

The menu will not update automatically, you'll have to save/update your terms to update the menu (hook_taxonomy_menu_update). For new terms, it's going to work automatically  (hook_taxonomy_menu_insert).


How to edit the label color for published or not published in Admin? I tried to change the color of the text under the "Published" column of the node content listing.

I need the published text to be in green color and the unpublished text to be in red color.

In the view I have edited the output of the following field:

Administration: Nodes (Content)

Configure field: Content: Published

Rewrite Output :

[status]

Please check the screen shot for a better understanding.

There are some ways to do that, one may be the implementation of the following preprocess function: hook_preprocess_views_view_table. Here is a code sample:

/**
 * Implements hook_preprocess_views_view_table.
 */
function my_module_preprocess_views_view_table(&$vars) {
  $view = $vars['view'];
  $results = $vars['result'];
  if ($view->name == 'my_view_administration_nodes' ) {
    foreach ($results as $row => $result) {
      $vars['field_classes']['status'][$row] .= $result->node_status ? ' published' : ' not-published';
    }
  }
}


Display a list of a user's Organic Groups While searching, I've found a lot about how to programmatically add things to groups, but I'm wondering if there is a function that will take a parameter identifying the user and return a list of their groups.

Is there a function that takes user info and returns a list of groups for OG in Drupal 7?

You can use og_get_groups_by_user() for that.

  Get the group IDs of all the groups a user is an approved member of.

The API linked to above might be for OG 1.x, it's slightly different for OG 2.x.

 function og_get_groups_by_user($account = NULL, $group_type = NULL) {
 ...

For instance:

 global $user;
 $user_groups = og_get_groups_by_user($user, 'node');

The above example is not really great as $account defaults to current user and without $group_type you get all types of groups, not just node groups, but you get the general idea.


Views_infinite_scroll not working I'm using Drupal 8 latest stable version: 8.5.x

I have 2 blocks (Upcoming events and Past events).

On Past events views infinite scroll is working with a button enabled providing the user ability to view more. It has many items and the module works as designed.

Same structure Upcoming events block returning only one upcoming event. When user clicks view more button the page is returning nothing and even the one item listed get disappeared.

Ajax is enabled on both views, the only difference is that upcoming events is returning only one result.

How can i solve this?

Why don't you duplicate the view that works and just reconfigure the filter criteria to met your requirements?


Views date range filter adds weird condition I have a view for a content type. This content type has a date field (only date) and I have added and exposed a filter for this field ("date is between" option).
I have added and exposed a filter for other text field.
If I put a condition on the text field in the filter of the view, then it generate a weird SQL for the date field.

SELECT node_field_data.nid AS nid, node_field_data_node__field_liq_club.nid AS node_field_data_node__field_liq_club_nid
FROM
node_field_data node_field_data
LEFT JOIN node__field_liq_club node__field_liq_club ON node_field_data.nid = node__field_liq_club.entity_id AND node__field_liq_club.deleted = '0'
INNER JOIN node_field_data node_field_data_node__field_liq_club ON node__field_liq_club.field_liq_club_target_id = node_field_data_node__field_liq_club.nid
LEFT JOIN node__field_liq_ejercicio node__field_liq_ejercicio ON node_field_data.nid = node__field_liq_ejercicio.entity_id AND node__field_liq_ejercicio.deleted = '0'
LEFT JOIN node__field_liq_fechaliq node__field_liq_fechaliq ON node_field_data.nid = node__field_liq_fechaliq.entity_id AND node__field_liq_fechaliq.deleted = '0'
LEFT JOIN node__field_liq_fechapago node__field_liq_fechapago ON node_field_data.nid = node__field_liq_fechapago.entity_id AND node__field_liq_fechapago.deleted = '0'
WHERE
(node_field_data.status = '1') AND (node_field_data.type IN ('liquidacion')) AND (node__field_liq_ejercicio.field_liq_ejercicio_value = '2010') AND
((DATE_FORMAT(node__field_liq_fechaliq.field_liq_fechaliq_value, '%Y-%m-%d') BETWEEN DATE_FORMAT('2019-01-01T00:00:00', '%Y-%m-%d') AND DATE_FORMAT('2019-12-31T00:00:00', '%Y-%m-%d')))
AND ((DATE_FORMAT((node__field_liq_fechapago.field_liq_fechapago_value + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s') BETWEEN DATE_FORMAT(('2018-12-31T23:00:00' + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s') AND DATE_FORMAT(('2019-12-30T23:00:00' + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s')))
LIMIT 25 OFFSET 0

My text field add the condition:
node__field_liq_ejercicio.field_liq_ejercicio_value = '2010'

But, although I don't fill any condition for date-range, it adds:

    and ((DATE_FORMAT(node__field_liq_fechaliq.field_liq_fechaliq_value, '%Y-%m-%d') BETWEEN DATE_FORMAT('2019-01-01T00:00:00', '%Y-%m-%d') AND DATE_FORMAT('2019-12-31T00:00:00', '%Y-%m-%d')))
AND ((DATE_FORMAT((node__field_liq_fechapago.field_liq_fechapago_value + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s') BETWEEN DATE_FORMAT(('2018-12-31T23:00:00' + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s') AND DATE_FORMAT(('2019-12-30T23:00:00' + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s')))

I don't know why it is added, and how to solve this issue. Why this INTERVAL 7200 SECOND?. Any suggestion?

After some test I have found that a module was changing filter form states, and then the filter fields were wrong when the query were constructed. I fix that and now it works good.


How to implement a multi step approval with webforms/entityforms based on form components? Is it possible to invoke multi-step submission workflow using either Webform or Entityform? Here is the scenario of workflows:

  An employee submits the form

  Superviser gets notification, after reviewing the form, he either approves it or denies the request on the same submission.
  If approved, an email notification gets sent out to Director who in turn approves or disapproves the same submission.

  If denied by supervisor, an email gets sent to an employee.

This scenario involves submissions by multiple roles to the same request. I could hide approval fields to employee role, but how would one access webform approval field component via rules for notification purposes? How would I freeze form state?

Should I rather use entityforms since every form component is exposed? As a last resort, I might implement my own solution using forms_api. But I would like to know first if it is possible using webform or entityforms.

Implementing this workflow is possible by using a combination of these modules (and regular content types, no need for something like "webforms"):

Rules.
Node Convert.
Flag.
Content Access.

Refer to my answer in the question about
"How can I allow anonymous visitors to submit content?" for examples (and more details) about how to use these 4 modules together (this question here seems like a variation of that question).

Below are some details to implement your workflow with a similar approach:

  An employee submits the form

Employee create a node of content type (say) "Request" (Use Content Access to finetune all sorts of permissions about "which role is allowed to create such types, if you have multiple types of requests you just extend to multipple content types).

  Supervisor gets notification, after reviewing the form, he either approves it or denies the request on the same submission.

Use Rules to "send an eMail" (= action) to Supervisor "After content of type 'Request' gets saved" (= event). In the (custom) eMail for the Supervisor, include all relevant details about the Request (depending on the various data that are available to Rules). Such as an URL of the node to be reviewed.
To ensure the Requestor cannot change the Request data (while the review process is outstanding), add an extra action to the same (previous) rule which updates the access to the Request (to make it read only for requestor).
Use the Flag module to enable the Supervisor(s) to mark the submitted node with flags such as 'Approved (by Supervisor)' or 'Denied (by Supervisor)' (Rejected?). The permission to set these flags is limited to the Supervisor(s).

  If approved, an email notification gets sent out to Director who in turn approves or disapproves the same submission.

Use Rules (again) so that "After a node gets flagged with 'Approved (by Supervisor)'" (= event), it causes a similar "send an eMail" (= action) to Director occurs. In the (custom) eMail for the director, include all relevant details about the Request (depending on the various data that are available to Rules). Such as an URL of the node to be reviewed.
Use the Flag module (again) to enable the Director to mark the submitted node with flags such as 'Approved (by Director)' or 'Denied (by Director)'. The permission to set these flags is limited to the Director.
Use Rules to "send an eMail" (= action) to Requestor "After content of type 'Request' gets flagged as denied (by Director)" (= event).

  If denied by supervisor, an email gets sent to an employee.

Use Rules to "send an eMail" (= action) to Requestor "After content of type 'Request' gets flagged as denied (by Supervisor)" (= event).

So just some basic Rules/Flag stuff ...

It does not (yet) include anything related to Node Convert. This module only needs to be added to this mix if you want to further refine the above with specific "fields" that some of the workflow participants should not "see" at all (to avoid you'd have to use "field permissions", which could be an alternative to that.

Possible enhancements

Form Block

I've no experience with the Form Block module. On its project page it says "Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.".

It seems to me that if you're using panels then there is possibly some added value when using this module. However, I'm not convinced (yet) about the real added value of this module.

There are a few things though that seem to me like red flags (= I'd think twice before using that module):

Where is the documentation?

Apart from what it says on the project page, there is (a) no community documentation (at least not linked to from the project page) and (b) some readme.txt that comes with the module, but with no "real" content.
Where is the D7 release?

There is an official release available for D6. But a D7 version only exists as an alfa 1, which is over a year old. And then there is a D8 version in beta status already. Not sure what is coming up in D8, but for D7 there seems to be something wrong. Is there ever going to be an official D7 version? Nevertheless, looking at the usage statistics there are a lot of D7 sites. Close to 10K reported installs for that D7-alfa version. 10K sites using the modules can't be wrong, so it must be something like "that alfa1 version is virtually an official release that should be tagged like so".

The above bullets are just a few of the criteria I often use for deciding on contributed modules. Refer to the community documentation about Maintenance Scorecards for more details. Here is the intro about it (from that page):

  ... contains a list of 23 criteria (=28-5) that might help to evaluate
  the maintenance and support of contributed modules. Below is an
  attempt to apply those criteria to each of the native charting modules
  ...

Obvious, these scorecards are related to "charting modules", but the same criteria are applicable, IMHO, wheneven you need to decide between multiple modules.

Bean

Maybe consider adding another module in the area of Blocks, by looking at the Bean module. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

Combined with the options available for granting the appropriate Bean permissions, it should give you a lot of flexibility about how exactly you want to use this (great) module in your specific case. As a bonus, the Bean module also works great in combination with the UUID and UUID Features Integration modules. On top of that, after you become familiar with the Bean module, you might find other cases in your site where you also want to use the Bean module (which somehow compensates the fact that you need to add another module).

Video tutorials

If you're not familiar with Rules, checkout the video tutorials Learn the Rules framework. And/or the similar set of 8 video tutorials about the Flag module.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of the Bean module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.


Path Breadcrumbs adds unwanted space in link path, why and how can I avoid it? I added in the link path field for a breadcrumb the following:

%site:url%node:tax-title-for-url-construction

"%node:tax-title-for-url-construction" is a custom token which returns a taxonomy title like "Xbox 360" in a cleaner way "xbox-360".

So the links should look like http://domain.com/xbox-360 but it return the following http://domain.com/ xbox-360 Note the space between site url and tax title, but there is no space in the link path field within the breadcrumbs configuration. So where does this space come from?

Here is the code from my custom token:

<?php
$node = node_load(arg(1));
$rtaxidarray = field_get_items('node', $node, 'field_plattform');
$rtaxid = $rtaxidarray[0]["tid"];    // taxid sauber
$term = taxonomy_term_load($rtaxid);
$name = $term->name;
$small = strtolower($name);
$clean = str_replace(" ", "-", $small);
return $clean;
?>

HM There was a space before the opening php tag in the custom token value field, I really hate spaces. I think spaces should be exchanged with a X ;)


Which files should I delete after a Drupal installation? After installing Drupal, there are files in the root directory that I should delete. I know that install.php is one of those. Which other files should I delete?

You shouldn't really delete any files. If you really wanted to, you could delete the install file and various txt files, but that's about it. A better solution if you are afraid of security is to not let the files be accessed through the web server. Drupal only use the index.php file for serving content.


How do I use contextual filters and relationships to show related articles? So, I've been trying to get this figured out for most of the day. I had it essentially working in the previewer at one point, but now it doesn't seem to work at all.

Use case: each node published with the content type "Article" comes with a Taxonomy field for included tags. What I'm trying to do is to create a block that appears under the article with a series of thumbnails that link to other articles. These articles in turn are related based on the tags used in each article.

So, the question is:

What would be a good way to set this up using Contextual Filters and Views to have the View itself automatically see the field_tags used as a Taxonomy term reference in an Article, and have it automatically display the output based on the tags of each article?

I've tried setting up the Contextual Filter to be aware that the terms would be in the Content Type: Articles via the Relationships filter, but frankly I'm kind of stumped as to what I need to do to even accomplish this.

I have implemented the same in one project in Drupal 7 to display products of same catalog.

You can create a views of article content and can create a contextual filters for tags. It will display all the article of that tags.

You can follow below step:

Add a contextual filter of tags. Checked radio button "Provide default
value".
Select "Taxonomy term Id from url" in the type drop down.
Checked "Load default filter from node page" check box.
Checked "Limit terms by vocabulary" check box.
In the Vocabularies section, checked the check box of Vocabularies
(tags) which you want to add filter in the views.
Under the more section, checked "Allow multiple values" check box, so
multiple tags can use filter the term.

You can find below image for reference.

You also need to add contextual filter of node id and follow below step, so current node page will not display in related views section.

Add content: Nid contextual filter in the views.
Checked "Provide default value" radio button and select "Content id
from url" in the type drop down.
Under the more section in contextual filter, checked "Exclude" check
box.


Display Special Characters in Drupal Forms API I have a variable fetch from database which contains special character ñ. For Example:

$student = 'Evangeline O. MontañO';
$student = 'Rosalyn G. QuiñO';

Displaying it in my form causes ajax error, but when I use check_plain function it returns an empty string and no ajax error occur. How can I display a variable with special characters on it without causing ajax error?

I suspect you need to add <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> into html.tpl.php in your theme. This isn't an issue with Drupal, but your browser not recognising the UTF8 characters.


How to restrict node access to nodes based on field value? Im making simple private message system (no need privatemsg), just node with title, body, and user reference field (entity_reference) for recipient(s). How can I restrict access to node only for node author, and users listed in field?

I think the Node Access User Reference module will do exactly what you want.  It allows you to restrict access to a node based upon a user reference field in that node. It even comes in Drupal 6 and 7 flavors.

From what I can tell though, you want to make sure you use only one node access module for your system, so you may want to look at the Node Access Module Overview to make sure this is the best bet.


How to show specific rows within an unlimited field group? I am trying to assign value to unlimited field group on load of content using form alter hook. Value get assign successfully for all rows. But when form get loaded it display only one row. On click of "Add Another Item", it display second row with value assigned in form alter hook.

Is there any way to display number of rows as required? Can I handle this in form alter hook?

Yes you can do it by form_alter. Seeing through the code of other similar question, I see that unsetting the Add More button can do it for. You can review that code & apply for your case.

You can do it by help of Field Validation module too, which has been mentioned in 2nd answer & more feasible way. I have also used it for some projects of mine, where I did set minimum & maximum required for a field accepting multiple values.


Referencing a paragraph field in a field--node template I need to reference field_role from a paragraph inside of a field--node template. The paragraph is an unlimited repeating field in the content type. The field template I am working with is the field in the content type which references the paragraph entity.

In the field template:

{% for item in items %}

    {{ paragraph.field_role }}

{% endfor %}

I've tried {{ content.field_role }} and {{ item.field_role }} as well.

Separately, I've also tried creating a preprocess hook for the field.

function theme_preprocess_field(&$variables, $hook) {
  $paragraph = $variables['paragraph']->field_role->value;
  $variables['var_role'] = $paragraph;
}

function theme_preprocess_entity(&$variables) {
  if ($variables['entity_type'] == 'paragraphs_item') {
    if(isset($variables['elements']['field_role']['#items'][0]['value'])){
      $variables['var_role'] = $variables['elements']['field_role']['#items'][0]['value'];
    }
  }
}

(I know this would only pull the first item from the repeating field, but I'm just trying to get anything to render at this point.)

How can I achieve what I am trying to do?

I was able to solve this by using the following in the field template:

{% for item in items %}
  {{ item.content['#paragraph'].field_role.0.value|striptags }}
{% endfor %}


How to put a comma between city and state in addressfield display? I'm using the addressfield module with Drupal 7.10.  I want a comma after the city name when displaying the addressfield.  Currently addresses display like:

123 Main St
SomeCity California 90100

I want it to display like:

123 Main St
SomeCity, California 90100

(Note the comma after "SomeCity")

How can I achieve this?

UPDATE

This whole formatting of addresses is still shrouded in mystery for me.  I'm starting to think the way to control the formatting is to create a custom ctools plugin.  I found this api documentation:

http://api.drupalhelp.net/api/addressfield/addressfield.module/group/addressfield_format/7

I'm going to explore it.

This is actually pretty simple, once you know the hooks and have some example code. You're correct that you need to use the ctools plugin api. So in a custom module, add:

/**
 * Implements hook_ctools_plugin_directory().
 */
function mymodule_ctools_plugin_directory($module, $plugin) {
  if ($module == 'addressfield') {
    return 'plugins/addressfield/' . $plugin;
  }
}

Then you drop plugin files in the directory you specified, within your custom module. In this case, plugins/addressfield. A file that will do what you're looking for would contain something like this:

<?php
/**
 * @file
 * city-comma.inc
 *
 * Adding comma after city.
 */

/**
 * Plugin definition for address field format.
 */
$plugin = array(
  'title' => t('Comma after city.'),
  'format callback' => 'mymodule_city_comma',
  'type' => 'address',
  'weight' => -80,
);

/**
 * Callback for plugin definition.
 */
function mymodule_city_comma(&$format, $address, $context = array()) {
  if (in_array($address['country'], array('US', 'CA'))) {
    if ($context['mode'] == 'render') {
      // Add comma after city.
      $format['locality_block']['locality']['#suffix'] = ',';
    }
  }
}

This file would actually go in a directory called 'formats' inside the directory defined in the hook. So: mymodule/plugins/formats/city-comma.inc.


When using the batch API, can I setup multiple batch jobs or can I only setup one batch with multiple operations? When using the batch API, can I setup multiple batch jobs or can I only setup one batch with multiple operations? I ask because of a data migration I am doing.

Also, will it run the batches and operations in the order they are received or are they run concurrently? I need to have some items imported before others. So I am concerned about this.

You can call batch_set() more than one time, and batch_process() will execute all the batch sets that have been set with every call to batch_set().

Normally a module will call batch_set() once, and pass as $batch['operations'] an array containing all the functions to call, but if two different modules are setting their own batch sets, they will be both executed.


How would I print out the first instance of a paragraph bundle in a node template? I have a node type article with a paragraph field field_sections with the available bundles section_image and section_text.  In my node.html.twig file I'd like to render out the first instance of any section_image bundles that may have been added. Any ideas on how to achieve this? Not sure if twig logic is correct way to go about this or if I should have a function in my .theme file that does the logic and returns a variable to do this that I could use in the twig file.

TWIG

In twig you can check for the paragraph bundle in the items loop of a field template and only print the first item found:

field--node--field-paragraph--content-type.html.twig

  <div{{ attributes }}>
    {% for item in items if item.content['#paragraph'].bundle == 'paragraph_type' %}
      {% if loop.index == 1 %}
        <div{{ item.attributes }}>{{ item.content }}</div>
      {% endif %}
    {% endfor %}
  </div>

And then print this field in the node template:

{{ content.field_paragraph }}

UI

For a UI solution you need a field formatter like Paragraphs summary formatter, which in the moment only exists in a sandbox version, see https://www.drupal.org/project/paragraphs_summary/issues/2803859#comment-11804075


Get content of current user + Of the users that are flagged or followed I have a site, where users can follow each other using Flag. Currently, I am able to create a view which shows content from all the user the currently logged in user is following. This is done adding a relationship to the flag.

What I am creating is a feed of posts, like in Facebook. So it should also show content posted by the current user along with user followed. But I am unable to do that unless the user follows himself.

In the relationship's settings, uncheck the setting that restricts content to that flag.

Use the regular view filters instead and have two filters with OR between them. They would probably be author: current and author: flag.


How to add the User:Picture field on the account registration form? I saw the User:Picture field after setting the User:uid contextual filter for a Views block. Now I am wondering how to show this field on the account registration form? I looked at config/people/accounts/fields but nothing there.

Any help is appreciated.

You can use Register with Picture module.

  This module exposes the 'upload picture' element to the registration
  form. It also gives you the ability to set a picture as required in
  the module settings.

  Drupal 7 Instructions

  Install and enable the module
  Navigate to: Configuration -> Account Settings. (admin/config/people/accounts)
  Check Enable user pictures if it isn't checked already.
  Confirm Enable pictures on registration is checked.
  Use the Registration Picture Field Weight field to adjust the display order of the picture field on the registration form. It can be
  a negative or positive number.


Get current node's count (rank/order?) from node.tpl in a View which renders a list of nodes I have a view that lists multiple article nodes.
Now for each rendered node, I want to be able to know its rank/order from the list of displayed nodes.

Here's a visual representation:

[view]
    [node.tpl] $count=1 [/node.tpl]
    [node.tpl] $count=2 [/node.tpl]
    [node.tpl] $count=3 [/node.tpl]
    [node.tpl] $count=4 [/node.tpl]
    ...
[/view]

For the first rendered node, I will be able to access a variable called $count whose value is set to 1 because it's the first and so on.

Btw, I'm using Rendered entity so I'm using node.tpl not views/rows templates

Ok it looks like there's a similar thread but worded differently.

How to add classes to every X number of node in a array


How is comment widget controlled In the core within the comment module a widget is provided by CommentWidget.php file (namespaceDrupal\comment\Plugin\Field\FieldWidget;). In this widget comment settings like open, close, hidden is provided. I am able to understand its working but not able to find from where it is being further controlled. By controlling I mean where in module (node or comment) status of comment is being processed, how the node decides whether it should show comments or not. Please tell me the file in the core where I should be looking for the code which does this processing. Thanks.

It's not being controlled, it controls.

The widget allows you to edit the comment status of a given node/entity. That is stored in the comment field, and the comment formatter, that displays the comments/comment form is then using it to decide what to show.


How does Drupal handle concurrent user creation? I can't understand a specific part of the Drupal code, namely this snippet:

  $account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());

  // Allow 'created' to be set by the caller.
  if (!isset($account->created)) {
    $account->created = REQUEST_TIME;
  }

  $success = drupal_write_record('users', $account);

This is from the Drupal 7 code

My question is about concurrency. I imagined that two concurrent sessions are executing this and because the lack of transaction handling here they might try to insert two records with the same uid.

Can you tell me why this works in production? How is it possible that Drupal uses no transaction management although for example creating a node usually involves writing records into many different tables.

How is it possible that Drupal uses no transaction management?

It's not. The code you're querying is part of user_save(); the very first line in that function is:

$transaction = db_transaction();

The rest of the function is wrapped in a try...catch that explicitly rolls back the transaction upon exception. The same is true for node_save(), and plenty of other core functions that require transactions.

See the db_transaction() docs for more info.


Missing edit button on node page Im allowing authenticated users to add field values on existing nodes on my site using the "Field Permissions" module. I`ve set up the necessary custom permissions in the "manage fields" screen:

However, an authenticated user is never shown the "Edit" button on the node page:

If everything where working, the user should have a "Edit" button to be able to add field values. What`s wrong?

The Field Permissions is so the field shows up, they can see it, when they are editing the node.

The problem here looks to be that they don't have permission to edit the content type node.

Ex:

Allow to Edit Own Articles
Allow to Edit All Articles


Group entitiy queries for a specific content type using Taxonomy Term Using Drupal 8 entity query I'm trying to figure how I can fetch values from a specific content type and group them that are associated via a specific taxonomy term.

As seen in the screenshot below I have an entity field called Group Schedule that is currently binded to a Taxonomy Term. Is there way I could group those entities that are assigned to a specific taxonomy?

Group Schedule Name (field_group_sched)
First Schedule (field_created_date)
Second Schedule (field_created_date)

Group Schedule Name 2 (field_group_sched)
First Schedule (field_created_date)
Second Schedule (field_created_date)

So far I've managed to fetch the values from the Schedule Content type

// Entity Query for Schedule Node Type
$scheduleType = $query->get('node')
    ->condition('status', 1, '=')
    ->condition('type', 'schedule')
    ->condition('field_associated_programs', $nid_degree, '=')
    ->sort('created')
    ->execute();

foreach ($scheduleType as $key => $program) {

    $programNode = _nodeLoad($program);

    $variables['schedule_content'][$key]['schedule_group'] = $programNode->get('field_group_sched')->value;
    $variables['schedule_content'][$key]['schedule_name'] = $programNode->get('field_schedule_name')->value;
    $variables['schedule_content'][$key]['schedule_date'] = $programNode->get('field_created_date')->value;

}

{% for program in schedule_content %}

{{ program['schedule_group'] }}

    {{ program['schedule_date'] }}

{% endfor %}

Ok well here we go if i understand you correct you want nodes linked by a entity reff field value:
in your example "field_group_sched" the see the below condition
but later you can just group stuff by anything you want

   // this is the known term id.
    $group_term_id = 1;
    // for Entity ref use field_name.target_id
    $query = \Drupal::entityQuery('node')
      ->condition('status', 1, '=')
      ->condition('type', 'schedule')
      ->condition('field_group_sched.target_id', $group_term_id, '=')
      ->sort('created');

    $entity_ids = $query->execute();
    if (count($entity_ids) != 0) {
      $entities = \Drupal::entityTypeManager()
        ->getStorage('node')
        ->loadMultiple($entity_ids);
      // dump($entities); // requires var dummper
      if (count($entities) != 0) {
        $group1 = [];
        $group2 = [];
        // then you can play with order or whatever you want here.
        foreach ($entities as $node) {
          // These are the loaded nodes;
          $title = $node->getTitle();
          $field_name  = $node->field_schedule_name->value;
          // if the schedule_name is "beer" put in to group 1
          if ($field_name == 'beer') {
            $group1[] = $node;
          }
          else {
            $group2[]= $node;
          }
        }
        // SEND your Nodes to the template here.
      }
    }


Issue with db_query related to date I am using created date of ubercart order to compare with filter selected values of date.

created date is in timestamp with time. Where as filter selected values it is just date and if try to convert the date to timestamp, its not fetching accurate results as per filtered dates.

I have attached the image for clear understanding.

I have used this as query:

$query = $query->condition('uc.created',array($from_timestamp,$to_timestamp),'BETWEEN');

Any suggestions ? Thanks in advance.

Instead of using different select boxes for month, date and year, you could use date_popup type.

$form['start'] = array(
    '#title' => t('Arrive'),
    '#type' => 'date_popup',
    '#default_value' => 'YYYY-MM-DD 00:00:00',
    '#date_year_range' => '0:+3',
    '#size' => 12,
    '#required' => true,
  );

Which comes with time field, so you will have the timestamp. Thats it, now you can compare the timestamp input to the database value.


path_set_alias() generates the wrong alias, and creates a 301 redirect to the desired alias's path I'm creating a webform when organic groups are created and I'm trying to set an alias for it with hook_nodeapi(). It successfully creates the alias when the insert operation for the group is called after the webform has been created and associated to the group, but if you edit and update the group it does not update the alias with the code I have written. and a SQL error is displayed.

Here is the code that is called by hook_nodeapi() on insert and update operations:

// Webform
$nid = $node->field_webform_id[0]['value'];
$webform = db_fetch_object(db_query("SELECT count(src) as total FROM {url_alias} WHERE src = 'node/%d'", $nid));
if ($webform->total > 0) {
  db_query("DELETE FROM {url_alias} WHERE src LIKE 'node/%d'", $nid);
}
path_set_alias('node/'.$nid, 'local/'.$state.'/'.$county.'/submit-tip');

I'm getting the webform node ID from a CCK field on the group, checking if there are aliases set already for that node, and deleting them from the url_alias table. Then I'm using path_set_alias to recreate an alias (in this case it is the same as before).

The error message displayed when updating a group:

  user warning: Duplicate entry 'local/pa/adams/submit-tip-' for key
  'source_language' query: INSERT INTO path_redirect (source, redirect,
  query, fragment, language, type, last_used) VALUES
  ('local/pa/adams/submit-tip', 'node/209', '', '', '', 301, 1311098626)
  in
  /var/aegir/platforms/crimewatchpa-dev-v2011-07-12-15-42/includes/common.inc
  on line 3538.

Instead of creating local/pa/adams/submit-tip as an alias to node/209, it creates an alias submit-tip-0 (submit-tip already exists on another node). A 301 redirect is also created with the path: local/pa/adams/submit-tip to node/209.

The trick was to set $node->pathauto_perform_alias = FALSE; before calling node_save.  Then my manual aliasing was allowed to take effect.

I still haven't figured out how to prevent the 301 redirect.  It only produces a warning now, and the alias stays the way I want.


Admin menu layout for my nodes I have a simple question: i need to use the layout and structure of drupal admin menu for my own nodes.
I need to replicate the structure and the feeling of admin menu and the page design for my nodes, how can i do that?
I need to replicate exactly the way the admin menu acts and feel on the body part of the site, so with two columns, groups of subtopic for each main topic, links listing for each level and my nodes as leafs of this structure.
Since this is already done on the admin menu, it should be possible to do it also with my own nodes, but how?
I am using Drupal 6

My thoughts are that you could use views to list various categories of nodes. And to have a similar layout structure, I haven't used it but I think Panels might help.

An alternative to Panels which I have used in the wonderful homebox module


Javascript only runs when logged in as admin I created a test site. I put the JS into the template.php:

drupal_add_js('jQuery(document).ready(function(){jQuery(".foomo").accordion({ collapsible: true, active: false, animated: true});});', 'inline');

File permissions are set as described here.

If I load the website as 'admin' the accordion is collapsed as I want.

But why doesn't open or close the accordion for any other user?

I switched to the views_accordion module, which works perfect:
embedded views wrapped by views_accordion


"changed by" on nodes mysql> select nid, uid, created, changed from node;
+-----+-----+------------+------------+
| nid | uid | created    | changed    |
+-----+-----+------------+------------+
|   1 |   8 | 1336040166 | 1336046390 |
+-----+-----+------------+------------+

I'd like to have an "changed by" column on the node table, exactly as we have a "created by" (the uid field). This would keep track of who made the last change on that node. I know that this could be derived from the node_revision table but this depends on the revisions being enabled for the content types I'm interested.

So, what is the best way to do this? And why doesn't Drupal core offer this by default? I thought that "changed by" is a pretty standard piece of information that a CMS should attach to content.

I thought this would be quite tough to do, but as it turns out it's fairly easy.

You just need to create a custom module that adds a column to the node table on install, implement hook_schema_alter() so Drupal knows about the new column, and add some logic to provide a value before the node is saved.

Here's a small module that will do the trick:

File: node_table_alter.info

name = Node Table Alter
core = 7.x

File: node_table_alter.install

function node_table_alter_install() {
  // Add the new field to the node table
  $field = array(
    'description' => 'Stores the user id of the last user to alter the node',
    'type' => 'int',
    'unsigned' => TRUE
  );

  db_add_field('node', 'changed_by', $field);
}

File: node_table_alter.module

function node_table_alter_schema_alter(&$schema) {
  // Add the new field to the schema cache
  $schema['node']['fields']['changed_by'] = array(
    'description' => 'Stores the user id of the last user to alter the node',
    'type' => 'int',
    'unsigned' => TRUE
  );
}

function node_table_alter_node_presave($node) {
  // Populate the changed_by column with current user's id
  $node->changed_by = $GLOBALS['user']->uid;
}

You may want to add logic to remove the field again on uninstall, and add an index to the table for the changed_by column (see db_add_index()), but this should give you a good place to start.

The beauty of this method is that you have effectively added a new property to the node. You'll be able to use node_load(), EntityFieldQuerys, etc. with it as if it were any of the other standard properties for a node.

God bless Drupal for being so extendable!


How can I have a block show only on the /user page, but only for users with specific role? I have users with the role "authors" and a block in /user showing publications so that visitors can see the publications of every "author". The problem is that the block is showing at every user profile page even if the user has not an "author" role. How can i set this block to show only to user profile pages that have a role "author"?

On the configure block page, at the bottom in the vertical tab menu, click on the roles tab, and select which user role you want it to display for.


How add sorting by Flag counter in Controller? I get node list in my Conroller:

$query = \Drupal::entityQuery('node')
  ->condition('status', 1)
  ->pager(10)
  ->sort('created' , 'DESC');
$nids = $query->execute();

How can add sorting by Flag counter?

The flag count in another table called flag_counts so you should do join with node table try the following:

$database = \Drupal::database();
$query = $database->select('node', 'n');
$query->fields('n', [])
  ->condition('nfd.status', '1', '=');
// Inner join to get the node status.
$query->innerJoin('node_field_data', 'nfd', 'nfd.nid = n.nid');
// This join to get the flag counts by node.
$query->leftJoin('flag_counts', 'fc', 'n.nid = fc.entity_id');
$query->fields('fc', ['entity_id', 'count']);
// Sort by count.
$query->orderBy('fc.count', 'DESC');
$query->range(0, 10);
$result = $query->execute()->fetchAll();


How to use values from a referencing node (parent) in a referenced node (child) On a Drupal 7 site, we have two node types, one called "Collection" (parent node type) and one called "Fabric" (child node type). Collections and Fabrics are connected through an entityreference field.

We want to have a pair of values defined on the Collection node, which is then selected in various combinations for each Fabric node. These are "Colorway" and "Design". We'll define for example 3 Colorways and 8 designs for a given Collection. And when we create each Fabric for that Collection, we will choose one Colorway and one Design - there is always one value from each as a pair.

Most of the time, these values will be defined when creating the Collection node. But occasionally, we will want to add a Fabric node independently. If the needed value (e.g., the new Fabric's colorway) does not already exist, we want to be able to add it via the Fabric node/add form and have it saved back to the Collection so that the value collection's value list remains in sync.

We're wondering what the most future-proof and scalable way to build this would be. We couldn't find any ready-to-go modules to do this. We considered using taxonomy, but it doesn't seem like a good fit (though it does feel like it should be some kind of node-centered taxonomy). It feels like this should be done with fields (and some custom code to do the synching), but maybe a different approach is better?

Have you considered looking at how commerce kickstart solves this same issue?  Collections are taxonomy terms and Fabrics are products.


Should I pass the $form parameter when building system_settings_form? Usually I refer to core for best practices. When I was building a system settings form I copied and repurposed the following core implementation.

This define the path for the system setting form that gets invoked via drupal_get_form()

  $items['admin/structure/menu/settings'] = array(
    'title' => 'Settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_configure'),
    'access arguments' => array('administer menu'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 5,
    'file' => 'menu.admin.inc',
    );

And this is the function that build the form:

       /**
        * Menu callback; Build the form presenting menu configuration options.
        */
        function menu_configure() {
          // The form definition is here ..
          //.....

        return system_settings_form($form);
       }

So my question is why isn't the $form param passed to the form function menu_configure()?
There are other examples of system settings forms in core, called via the drupal_get_from() that do not have the $form parameter in the parameter list. So is it optional in this case?

The form parameter is passed from drupal_get_form(), but if you choose to start a new form array it doesn't really matter. The form works as expected.

However, it's good practice I think to include $form and $form_state in the parameter list because if you ever change your menu entry to pass an argument, then all you need to do in your form builder callback is to add it to the list at the end.


Content type with webform Hi All I have I issue for my content type
like

I have content type  of property    user can add property fields
this is  ok
My problem is  i have to add  static form every time . i want it
default of every content  type is it possible please give me
suggestion for this

There is a setting in Webform "Available as block" so, it will be Available as block, you can use this block in all node pages


How do I create a hidden field programatically? I've got a module that is creating fields programatically, all working so far. The code is below. This may be useful as-is if you are trying to create checkboxe fields from an array of values:

    /**
     * Helper function to create fields for workflow approvers
     *
     */

    function _create_approval_fields($approverRolesClean){
      $fieldPrefix = 'wf_';

      // TODO: If an existing field is removed, delete it.

      foreach ($approverRolesClean as $approverRole) {
        $cleanRole = preg_replace('/[^a-z]/', "", strtolower($approverRole));
        $fieldName = $fieldPrefix.$cleanRole;
        if (!field_info_field($fieldName)) {
          $field = array(
            'field_name' => $fieldName,
            'type' => 'list_boolean',
            'widget' => array(
              'type' => 'options_onoff',
              'settings' => array(
                'display_label' => '1',
              ),
            ),
            'settings' => array(
              'allowed_values' => array(
                '0' => 'No',
                '1' => 'Yes',
                ),
              ),
            );
          field_create_field($field);
        }
        //Hardcoded:
        if (!field_info_instance('node', $fieldName, 'contenttype')) {
          $instance = array(
            'field_name' => $fieldName,
            'entity_type' => 'node',
            'label' => 'Approved by ' . $approverRole,
            //Hardcoded:
            'bundle' => 'contenttype',
            'widget' => array(
              'type' => 'options_onoff',
              'settings' => array(
                'display_label' => '1',
              ),
            ),
          );
          field_create_instance($instance);
        }
      }
    }

I set the value of the fields outside the Edit screen - so they never need to show there. I'm sure there is a settings parameter that I can add to hide it, but not sure where to find the doc. I don't think no_ui is what I need.

Otherwise I can use the form api to hide it at render time, but that doesn't seem as elegant.

Thanks,

Jack

I don't follow the example 100%, but to answer the question - in D7 you can set '#type' => 'hidden', '#value' => 'foo' or just do '#my_custom_key' => 'my custom value' and it will be available to you in the submit handler (or elsewhere, such as hook_field_attach_submit()).


Views: Aggregations Do Not Group by a Date Field So, I am using Drupal 7.19 and Views 3.5. For some reason, I can not group by a date field no matter what!

I created a simple view that displays the number of nodes that have been published per month. As such, I selected the Nid and Post date fields, enable aggregation, count on Nid and group on Post date.

No grouping. There is a record being pulled for every single node in the database, as if the grouping is being completely ignored.

If you run the SQL statement Views generates on the database, you also get a complete result set but that is obviously because the UNIX time stamps themselves are different, if even my a second. That's expected. How can I get Views to group by a formatted value, such as a Month, Year, etc, to avoid this problem?

I tried everything suggested here and elsewhere - I already had the RDF module disabled, emptied cache, added a new date format, strip white space from the date field ,I even disabled the Date module for fear it was conflicting with it.

This is driving me absolutely crazy! Would appreciate any suggestions. Thanks.

To group on a date field just copy the contextual filter from the default archive view. No need for aggregation to be turned on.  Settings shown in pic:


Calculated field returns undefined index I'm trying to average all of the fivestar ratings I have for a node using a computed field. But i'm struggling to simply access the other fields using entity!

In the body of the node, this works fine:

$test1 = $node->field_ae_stimclasswrk[und][0]['average'];

In the computed field area, this doesn't work:

$entity_field[0]['value'] = $entity->field_ae_stimclasswrk[$entity->language][und][0]['average'];

Instead, when I save the node, I get this index error:

  Notice: Undefined index: und in eval() (line 2 of...

It must be something syntax, but I'm completely out of ideas.

Here is the field info:

    [field_ae_stimclasswrk] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [user] => 80
                            [average] => 80
                            [count] => 1
                        )

                )

        )

$entity->language is the same as und so try using:

$entity_field[0]['value'] = $entity->field_ae_stimclasswrk[$entity->language][0]['average'];


How to edit a node programatically after it has been created? My articles have a field 'Ranking' and I'd like to give a value to this field after a node has been created. The value depends on the node's ranking in a view called 'Top 3'. I tried the following in my custom module 'Top', but it doesn't work.

function top_node_insert($node) {
  $top = views_get_view_result('top_3');

  $found = false;
  foreach($top as $key => $value) {
    if ($value->nid == $node->nid) {
        $found = true;
        break;
    }
  }

  if ($found) $ranking = $key + 1;
  $node->field_hoogste_ranking[LANGUAGE_NONE][0]['value'] = $ranking;
}

What did I do wrong and what's the correct version?

If you look at the Node API Hooks description here, you will see that hook_node_insert is called after field_attach_insert. That means that at the point hook_node_insert is called the fields for the node are already written to the database. If you keep your code in top_node_insert, then add field_attach_update('node', $node) to update the fields with the new data. It might look something like this:

function top_node_insert($node) {
  $top = views_get_view_result('top_3');

  $found = false;
  foreach($top as $key => $value) {
    if ($value->nid == $node->nid) {
        $found = true;
        break;
    }
  }

  if ($found) {
    $ranking = $key + 1;
    $node->field_hoogste_ranking[LANGUAGE_NONE][0]['value'] = $ranking;
    field_attach_update('node', $node);
  }
}

Alternatively, you can try and use hook_node_presave.


Drupal behaviors attach to form load I am using the simpledialog module with the 'edit' tab still in it. The edit overlay for the node is displayed in the background with the simpledialog still in the way.

I have tried a bunch of ways of attaching the close call to the edit button and triggering a click on the dialog close button. None of it very successfully - all iframes. e.g.

$htj2('.tabs.primary').delegate('click', 'a', function() {
    $hjt2('#simple-dialog-container').dialog("close");

I think the 'correct drupal pattern' is to attach a behavior to the form load using drupal behaviors.

(function ($) {
    Drupal.bahaviors.hotTopicsResearch = {
        attach: function(context, settings) {
            // ?? What next?
            $('#hot-topic-research-node-form',context).once('load', function() {

            });
        }
    }
})(jQuery);

How do I find out what the behaviours are? How do I attach to the load event or is there an event related to clicking on the 'edit' tab? How do I get close the simpledialog?

Got it after a number of days searching:

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

            $(document).bind('drupalOverlayBeforeLoad', function(event) {
                $('#simple-dialog-container', context).dialog('close');
            });
        },
        weight: 11
    }

})(jQuery);

The other events seem to have the wrong order. 'drupalOverlayOpen' almost works except that the editing overlay never 'becomes active'. This is why I was trying to work on the target editing screen events rather than the open dialog.

overlay_paths without there being'use case documentation' it looks like it only applies to menu items. How to manually use Drupal 7's admin Overlay? shows you how to add content nodes to the admin paths. This displayed my node in the admin overlay, but without the background context being visible - defeating the point - and with some further quirks.


Increasing PHP memory limit (Possible Drupal override?) Problem

I've recently come across a problem with my dev version of Drupal where I realised the php memory limit isn't high enough.

I've changed the main php.ini files but they seem to be ignored and I can only increase the memory limit by putting the following line into sites/default/settings.php:

ini_set('memory_limit', '500M');

Could there be something Drupal related which is overriding the main settings (that I'm then overriding in settings.php) as this is happening in multiple environments?

Set-Up

Windows 7, XAMPP:

Altered php.ini in C:/XAMPP/php/php.ini

memory_limit=500M

Ubuntu(10.04), Apache, PHP, MySQL

Altered php.ini in /etc/php5/apache2/php.ini

memory_limit=500M

Ubuntu(12.04), nginx, PHP-FastCGI, MySQL

Altered php.ini in /etc/php5/cli/php.ini
(checked this was correct ini file using php --ini)

memory_limit=500M

I have a php.ini in my drupal root, but it has

memory_limit = -1

which I'm pretty sure is no limit.

Drupal does not edit any php config settings. The memory_limit and what php.ini it is using depends on how your server is setup, there could be something else that is overriding your php.ini you are trying to set. You should use phpinfo() to find out what php.ini it is using and make sure the last occurrence of memory_limit is set to what ever you want.


hook_cron() is not working I've created a new Drupal 7 module, which has been installed and enabled.

I have this function in the module.

function remove_entries_cron() {
  $query = "INSERT INTO {search_dataset} (sid,type,data) VALUES (22061986, node, hello)";
  db_query($query);
}

I have cleared the cache, and ran the cron manually but the record doesn't appear in the database.

Is there a way to check if the cron hook is working?

To check if a cron hook is being invoked, you need to output something to an existing database, for example using one of the following functions:

watchdog() requires you enabled the Database logging module; otherwise, no entry will be added to the watchdog table, and admin/reports/dblog would not show new entries
variable_set() always set a value in a database table, but the value returned from variable_get() could be the value set in the settings.php file for the $conf array
The database API functions can be used, but you need to be use the database table exists; for example, use a database table installed by a module, even if it a module of yours

In the second case, don't use a Drupal variable (e.g. this_is_a_wrong_variable), for which the following code exists in settings.php.

$conf['this_is_a_wrong_variable'] = 'This value will be always returned from variable_get().'

If you do so, whatever you set with variable_set('this_is_a_wrong_variable', 'My hook is invoked: ' . time()) will not be returned from variable_get() which would return 'This value will be always returned from variable_get().', in the example I made.

As you discovered, every Drupal hook must have a name prefixed by the module short name. In fact, the code used by Drupal to invoke a specific hook used by all the modules is the following one.

  foreach (module_implements($hook) as $module) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      $result = call_user_func_array($function, $args);
      if (isset($result) && is_array($result)) {
        $return = array_merge_recursive($return, $result);
      }
      elseif (isset($result)) {
        $return[] = $result;
      }
    }
  }

As you see the function name for the function implementating a hook is $module . '_' . $hook. For the Node module, the hook_cron() implementation would be node_cron(); for an hypothetical module_with_a_long_name module, the hook_cron() implementation would be module_with_a_long_name_cron().

Bear in mind that, if you edit the code of an enabled module to add a new hook, you need to disable and re-enable it, or Drupal will not see you added a new hook has been added to the module, since the list of hooks implemented by a module is cached. See module_implements().

  // Fetch implementations from cache.
  if (empty($implementations)) {
    $implementations = cache_get('module_implements', 'cache_bootstrap');
    if ($implementations === FALSE) {
      $implementations = array();
    }
    else {
      $implementations = $implementations->data;
    }
  }


How to hide tabs, depending on the role of editing using menu_alter I have 3 types of accounts: Admin, Student and Tutor.

After I turned on the path user / %user / edit / tutor, I see two tabs editing: Student and Tutor. But I want to only display the tab tutor when I edit tutor.

I'm using module profile, which adds tabs unknown way.

Any suggestions?

Using hook_menu_alter you put restriction by passing role in access argument like "tutor" or "student".

function MYMODULE_menu_alter(&$items) {
  $items['menu_item']['access callback'] = 'user_has_role',
  $items['menu_item']['access arguments'] = array('tutor'),
}

function user_has_role($roles) {
  if (user_is_logged_in()) {
    global $user;
    if (in_array('administrator', $user->roles)) {
      return TRUE;
    }
    foreach ($roles as $role) {
      if (in_array($role, $user->roles)) {
        return TRUE;
      }
    }
  }else {
    return FALSE;
  }
}


Display summary of entered field values and permit user to cancel submission Versions:
   Drupal 7.12
   Webform Module 3.17

I have webform that has multiple pages (using pagebreaks). When the user completes the final page I would like to display a summary of the entered information so that the user can double check it before submitting it.

My first thought (after much searching) was to:

Use the hook_webform_submission_presave hook to catch the submission before it is saved
Display the field values
If the user decides not to submit the form cancel the submission

However I am having difficulties applying the above theory to reality.

Is this possible?
Is the above method the best approach (if it is, how do I achieve it)?
Or is there a easier/better way to achieve this?

Any help would be appreciated......Kevin

There is a feature request for a "summary" component for Webform in the Webform module issue queue here: http://drupal.org/node/435232, but there isn't any movement yet on actually making a built-in summary component in the core project.

In that issue, dealancer notes that he has already added his code to the http://drupal.org/project/webform_bonus project, which allows you to add a summary component directly to your form in the same way you would add a textfield or any other component type. Install that module and add a summary field to your form, selecting which fields you would like to include in the summary. If you would like it on its own page, make sure to add a pagebreak component first.


Ignore parts of the url or dynamically rewrite/alias the url I am having a problem and have been wrecking my brain over it...

I feel I might ohh how did I not think of that moment once I find the solution...

Basically, what I need to do is:

For any url containing a string like "abcmytrack" show the page/view/drupal url that is before it in url and ignore the rest. So if I go to node/1/abcmytrack/some/other/stuff/abc then just show node/1, if I go to nodeone/alias/page/abcmytrack/some/other then again just show nodeone/alias, but keep abcmytrack/some/other in the url.

What am I trying to do:
there is some referral tracking that I am trying to implement in the form of.

/some/drupal/url/[trackid]/some/other/track/ids/even
/any/drupal/url/[trackid]/any/even/number/of/arguments
/[trackid]/some/other/set/of/arguments

basically for any url with [trackid] which is a string. It should just ignore anything starting with [trackid] and load the path before it as if [trackid] was not there.

The result is that they basically get converted to a cookie, but the site is behind varnish and akamai caching so on production the code does not run and cookie is not written.  Best option at the moment is to use JS to write a cookie, but problem is that adding /[trackid]/some/other/set/of/arguments to some of the site urls like aliased node paths, homepage, etc. breaks the pages.

It might be possible to do it as url rewrites in .htaccess but this is a last resort.  I would like to see if there are other options I am not considering.

I have attempted to do use hook_url_inbound_alter but it seems to do redirects and I loose the string from the url or otherwise it url encodes the string.

I have been wrecking my brain on this and cannot make this work. Granted I have some interesting requirements but it is one of those things that should be straightforward but it is not.

Subpathauto might do what you need even if it wasn't written for that exact use case. https://www.drupal.org/project/subpathauto

Subpathauto was written to handle the case where those extra arguments at the end of the string are meaningful and the first portion of the string is an alias. For that to function it must use hook_url_inbound_alter (you were on the right track!) to look up the first section of the string.

Even if this module isn't an exact fit the code within it is a good starting point.


Can't import configs on server due to some entities So when i try to manually import configs (/admin/config/development/configuration) i get these messages:

Entities exist of type Media and Media type Image. These entities need to be deleted before importing.
Entities exist of type Media and Media type File. These entities need to be deleted before importing.
Entities exist of type Content and Content type Media tester. These entities need to be deleted before importing.

Core is 8.6.1

Anyone know how to solve this?
Btw this is prod, so deleting content is a no go.

This is tricky to solve. And with the limited data provided in the question, there are a few steps that I would suggest you take:

Backup!!! No need to emphasize more as this is production environment. The following steps should be carried out on your local setup and not production.
Find out what changed in the entities. The change should most probably be in the field settings for one or more fields in the entity types listed in the messages. Check with the developer if you are not sure about the changes. If the changes are not desired, simply export the current configuration using drush cex and push it. If this is the case, then it will be ideal for all. If not continue to next step.
Since deleting the fields is not an option as it would delete the data, create a new field with exactly the same label but different machine name. These fields could have desired settings.
Write a script (update hook, migration, drush command - recommended, etc) which will copy the data from the original fields' to the new field with the correct settings.
This script could also then delete the field with the older setting which was preventing the config import.

Note: You need to consider the usage of the field at the implementation level and make sure you handle those. Like:

In any view mode for the entities.
In any view.
Any preprocess function.
If the field template has been overridden.

The data is very crucial here. So TEST, TEST, and TEST! Everything would be easy if there are a limited amount of entities with values in the conflicting fields and that the data could be handled manually by deleting the fields.