Drupal 8 Forms/Webforms Ajax Callback Elements I'm looking to add/edit elements on a Drupal 8 webform with Ajax Callbacks, I've read up on the buildForm technique, however my problem is a little more complicated, in that I am actually trying to do all of this inside of a custom composite element, not a form object.

Adding a new element via HtmlCommand is no problem, however any '#ajax' callbacks I add to this new element do not get initialised.

Thanks.

You can't add elements in an ajax callback:

  Note, that as part of the Form APIs security system, you cannot
  create new form elements in the callback function, as they will throw
  errors upon submission, and any #ajax on elements created in the
  callback will also not work. If you need to create new elements on
  ajax submit, they must be added in the form definition.

from https://www.drupal.org/docs/7/api/javascript-api/ajax-forms-in-drupal-7 (still valid for D8).

It should be possible to find a method in the composite element which is part of the form building process where you can add the form element.


There is data for this field in the database. The field settings can no longer be changed I have a content type where we reference Taxonomy terms in one of the fields. When the field was created it was set up to Unlimited entries for that field.

The issue is that we need to change this field from Unlimted to Limited to 1.

There are a few nodes where more than one term was referenced. Which means that we can no longer change this fields storage settings until the nodes that have more than one record are changed to 1 term only.

My questions is how to set up a view that will show only nodes that have two or more terms referenced.

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

What needs to be changed:
There are 65 entities with 2 or more values in this field.

Solution:
If we can change those 65 entries, I know we will be able to limit this filed to 1 term.

How?
The question is how do we find those nodes? I can't set up a view that will exclude nodes with 1 taxonomy term but show all with 2 or more.

I haven't tried to lower the settings in a situation where no extra data would prevent it, but it seems it is possible: Changing cardinality lower than highest existing delta causes data loss upon save.

But assuming it can be done, you can also create Views to list content with more than one term in a multi-valued field.

Fields with multiple values track the values with Delta starting from 0. Field with one value has Delta 0. Field with 2 values, has Delta of 0 for the first value, and Delta of 1 for the second value etc.

Field

Value 1 (Delta: 0)
Value 2 (Delta: 1)
Value 3 (Delta: 2)
…

Delta is available in Views. This means you can Filter content with regard to it, which is what you want.

Create Views of type Content with Filters and Fields appropriate for your initial situation, show Title and the Taxonomy field in question so you can check the results (you probably already have this covered)
Add a Filter of your field Delta. It will be called something like MyTags (field_mytags:delta). If you search for your field name it will list both your field and the Delta, choose the Delta option.
Set the Operator of the Delta Filter to Is equal to and enter 1

This will list all the nodes (provided your other filters are set appropriately) where the second position in the Taxonomy field isn't empty. Meaning there are at least 2 terms recorded in that field. The nodes will only be listed once.

If you set the Delta Filter Operator to Is greater than 0, as you may be tempted, it will also list the nodes that have more than one term in that field, but it will list them as many times as there are terms on that node minus 1. So if a node has 3 tags, it will be listed twice, because it will list one result for each Delta above 0.

With this result, you can go on to use Views Bulk operations to edit the listed "offenders", by coding an operation that deletes all but the first value from that field. Or even manually edit each node if coding is not an option.


Ubercart Discounts (Alternative) needs Content module I have installed Ubercart in Drupal 7. My client needs to be able to have special pricing for members, so I added Ubercart Discounts (Alternative). I also installed CCK as a per-requisite. However, the installed module says it needs the Content module. I am not able to find this module.

Content is the core module of CCK. You can find it under the CCK section of your module install page.


Cron tasks don't work: Could the Domain Access module be the cause? I have an issue with a website running Drupal 8. I cannot seem to get cron working. If I go to the status page and click 'run now' it works. If I try to open the cron settings (/admin/config/system/cron) I get an error. The log reports the following:

  Symfony\Component\Routing\Exception\InvalidParameterException: Parameter "key" for route "system.cron" must match "[^/]++" ("" given) to generate a corresponding URL. in Drupal\Core\Routing\UrlGenerator->doGenerate() (line 202 of /var/www/exin.com/files/core/lib/Drupal/Core/Routing/UrlGenerator.php).

I looked up the system.cron path in the core files and found it attached to /cron/{key}, so that is not the settings page. It is the URL I was supposed to use for the cron tasks. Calling that URL (replacing {key} with my token) generates a permission denied error, even if I open it when logged in as administrator.

I found the key on the status page by looking at the URL of the 'run now' button (/admin/reports/status/run-cron?token=mytoken). Is this the correct token?

I'm running Drupal 8.3.7, which was updated from version 8.3.1, where I had the same issue.

I'm also using the Domain access module and some creative nginx configuration to open different "domains" through a proxy, which (for example) takes users from www.mysite.com/fr/ to fr.mysite.com. This was necessary since the Domain access module could not work with subdirectories. It caused a lot of issues which we managed to resolve, but this one sticks. So I'm not sure it is caused by either this module or the nginx configuration, but I feel it is important information.

The error is coming obviously from these lines of code in the cron settings form, when it tries to build the cron link:

$cron_url = $this->url('system.cron', ['key' => $this->state->get('system.cron_key')], ['absolute' => TRUE]);
$form['cron_url'] = [
  '#markup' => '
' . t('To run cron from outside the site, go to @cron', [':cron' => $cron_url, '@cron' => $cron_url]) . '
',
];

So you somehow lost the State variable system.cron_key, which is on your site "" and causes the error. You find this in the database in the table key_value and collection state.

To set a new key you can rerun this code from system_install():

  // Populate the cron key state variable.
  $cron_key = \Drupal\Component\Utility\Crypt::randomBytesBase64(55);
  \Drupal::state()->set('system.cron_key', $cron_key);


Should i use field.tpl.php or Display suite to add my own classes to fields? I want to get rid of the default classes and add my own to the fields. I was always using field.tpl.php but i've read some tutorials where people are doing this with Display Suite. So should i do this via field.tpl.php or Display suite?

It's matter of opinion, really. I'm using DS and it works fine, but it might have disadvantages later on, because I will have to export my settings to code with Features.

Also, DS isn't your only option - you can also try:

https://www.drupal.org/project/semantic_fields
https://www.drupal.org/project/field_formatter_class

and others. Which depends on your other needs - for example, are you planning to use DS multiple display modes handling?


Adding JS to a specific URL I want to add some JS to a particular page.  In template.php, do I simply need to check request_path() in my preprocess_page() function in template.php?  Is that the best way to do it?

Yes, this is the function you are looking for:

function mythemename_preprocess_page(&$vars, $hook) {
  if(request_path() == 'your_path') {
    drupal_add_js(path_to_theme().'/js/yourjs.js');
  }

  $vars['scripts'] = drupal_get_js();
}

Request path is an easier way to do this than the < Drupal 6.x method of reading the arg() string (ex. if arg(0) === 'node' && arg(1) === 'some node id')


jQuery.browser.msie depreciated in 1.9 trying to fix in Drupal 7 The design template I am using needs jQuery 1.9. But Drupal 7 doesn't seem to support 1.9. Please correct me if I'm wrong
The issue is that when in import jQuery 1.9 in Drupal 7 then here is the following error when in admin (overlay) trying to add content:

 Uncaught TypeError: Cannot read property 'msie' of undefined

This is coming from overlay-parent.js. It has the following code:

if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {

It's causing an error because I am importing jQuery 1.9 and Drupal 7 runs code that contains the deprecated and removed jQuery.browser method.

The problem is that, after updating the code in  modules/overlay/overlay-parent.js to:

if (navigator.userAgent.match(/msie/i) && navigator.userAgent.match(/7/)) {

These changes are not taking effect. Perhaps this has to be compiled into some minimized .js file but I am not sure. How to make these changes in Drupal 7? Any alternative ways to make jQuery 1.9 compatible Drupal 7?

Drupal ships with a particular version of jQuery.

Using a different version of jQuery means refactoring various core javascript code.

If you want to use a more recent jQuery version, you can check the available versions provided by the jquery_update module which provides that refactored replacement javascript.


How to create a view that shows a Managing User all content of their members? I want to create a View that lists all content of authors who have the same value (text) as the viewing user. Actually they are members and the viewing user is the manager of the members. I have 2 profile fields that I think could be used to show the desired results:

1) an entity reference field called "field_ca_reference" to allow a member to reference a manager

2) a text field is set upon member verification that has the exact same value on both the member and the manager

How do I set up this view such that the manager sees all content of their members only?

First of all create a view of all content.

Next, add a relationship to the author of the content. Call the relationship author. Check 'require this relationship'.

Next, add a contextual filter on the entity reference field to the manager, using the author relationship. Under 'When the filter is not available' select 'Provide a default value', and choose 'User ID from logged in user'.

Let me know if it works for you.

I've added an image of my view for you:

And here is an export of my view - you should be able to import this and it will just work:

$view = new view();
$view->name = 'test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Test';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: User: CA reference (field_ca_reference) */
$handler->display->display_options['arguments']['field_ca_reference_target_id']['id'] = 'field_ca_reference_target_id';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['table'] = 'field_data_field_ca_reference';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['field'] = 'field_ca_reference_target_id';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['relationship'] = 'uid';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['default_action'] = 'default';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'test';


Passing arguments to the child view I'd like to ask a question concerning the Views field view module.

I can see in the parent view a list of tokens available to pass as arguments to the child view but I can't see any way to grab those arguments from within the child view.

How can I achieve this?

The recieving end doesn't require any configuration that's specific to Views field view. The arguments are passed on as if they came from the URL, so they are used just like regular arguments/contextual filters.

It's important to note that it's easy to completely wreak your server performance with this module. A medium-sized site could suddently execute a thousand views or so if this module is (ab)used.


Failure in "file module Update #8700" file module

Update #8700
•Failed: Drupal\Core\Field\FieldException: Field storage definition for 'type' could not be found. in Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema->getEntitySchema() (line 979 of /var/www/xxxxxxx.com/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php).

This message is shown after running update.php
I believe this is also related to a brand new problem we're having since the upgrade to 8.9.7 -- we can no longer add images.
Need advice for how to perform this update. At this point I just want it done, so even if I have to manually hack something I'm fine with that. I can revisit how to fix things properly once the site is working again.

This is probably connected to the module File Entity.
You find a patch in this issue:
https://www.drupal.org/project/file_entity/issues/3060204


In Commerce 2, is it possible to have the product variation automatically created during product creation? We have a Commerce 2 store whose products will always only have one variation.

The current workflow to create a new product and its variation is a bit complicated for the user's who will be entering in the product data.

Out of the box you have to click the 'create variation' button after entering in the variation information. There is then additional option buttons to Edit, Remove, or Duplicate the variation.

We'd like to streamline this process and have the single variation created automatically so all the user needs to do is enter a price during the product creation and not have to click any additional buttons.

I was hoping there was a module available that would facilitate this functionality but I was unable to find one.

If not module exists, what would be the best way to achieve this?

Perhaps a custom 'product' form that then creates the Commerce Product programmatically when the form is submitted? I don't really like this idea because I would also have to consider editing the product as well.

Would some custom code be able to tweak the existing workflow to hide the variation info and create it automatically? Perhaps getting the price from a custom price field added to the product entity?

Update to Commerce 2.10.

Then, edit your product type and uncheck the Allow each product to have multiple variations checkbox. This will give you a Product information fieldset on the product add/edit form with the variation fields.


Installed Drupal 8 in English, added Hebrew, deleted English and now site is malfunctioning I've deleted the English language from the site (testing purposes - long story) and now when I go to certain pages I get 404 errors (even in the page that will allow me to bring it back - admin/config/regional/language/add.

I guess adding & enabling the language with Drush-master could be helpful but I didn't find any such commands at drushcommands.com

I also tried the following Drupal 7 drush command variations (and others). None worked:

drush dl drush_english
drush dl drush_English
drush dl drush_en

Maybe there is a manual way to do so which isn't by the UI or Drush?

Ideas?

My solution is comprised of part1, and part 2:

Part 1

For some reason, from the moment I deleted the English, each time I went to the pages in the site, including the one I could it bring it back in (admin/config/regional/language/add) all of these urls included an "he" (Hebrew) part. For example the add language page was:

he/admin/config/regional/language

But when I changed the he to en (English) than for some reason I could re-add the English language!

But, even thought it seemed I finished with the problem, another one came in, which I also had to solve:

URL's in the site still redirected with "he" parts even after I deleted the Hebrew language from the language lists, and thus I couldn't even flush all caches from the ui because the URL that instructs cache flushing started with an "he" part.. in the following part 2 I will describe how I solved that:

Part 2

After I re-added English, and deleted the Hebrew language from the list, I went to the "Detection and selection" tab under "Languaes" at admin/config/regional/language/detection, and unchecked there the option URL: `Language from the URL (Path prefix or domain), and than I flushed all caches with Drush (the Drupal CLI) and the problem was solved.

I than re-added Hebrew and setted it default language without any problem; Since I changed it's influence on URL's under the "Detection and selection" tab at the Languages page, I didn't have the "he"\"en" parts problem after that.


Insert a collapsible fieldset or region in a panels layout I created a custom layout for a panels display and I would like to have a region or multiple regions in my custom layout be collapsible with javascript/jquery. Ideally the state of the collapible region would also be remembered by a cookie, but first thing is the collapsible functionality. Can anyone help?

<fieldset class="collapsible collapsed">
<legend>
Title of fieldset goes here.
</legend>
<p>
Content goes here.
</p>
</fieldset>

The best I've come up with so far is a custom module's hook_form_alter to create a fieldset and move fields in.  Note that in order to avoid something like:

Notice: Undefined index: field_txt_student_id in ctools_entity_form_field_content_type_render() (line 96 of [...]/sites/all/modules/contrib/ctools/plugins/content_types/form/entity_form_field.inc).

because the field is moved and unset(), it is not known by ctools to have been moved (or something).  Its render function does basic data sanity checking but then goes with the assumption that this field still exists by name where it was before the alter.

To get around that, instead of unset()'ing the original field, set it to a non-kind-of-field per this thread.

//  unset($form[$fieldname]);
$form[$fieldname] = array('#language' => NULL);

Would love to hear what other solutions exist!  I spilled my "solutions that don't work" in a comment on your original question.


How to add custom page.html.twig for views page? I have a view page with url and machine id search

I need to add a custom page.html.twig for that specific view page so that it does not affect the rest pages.

How can I implement it?

I tried adding page--search.html.twig but it did not work.

page--[url of your view].html.twig

Put the file in drupal/themes/YourTheme/templates folder

Remember to flush/clear the cache to see the changes.


importing XML file to create/update nodes, relation nodes/users, and taxonomy terms (to several vocabularies) Thanks for take time to read this question.

I want to import a XML file. XML content will create/update: nodes, relations nodes/users, and taxonomy terms (to several vocabularies) and his relation with nodes. I want to know, if is possible, your experiences and suggestions about this kind of requirements, or modules to resolve this, or if is best a custom code.

thanks in advance.

The migrate and migrate extras modules are your best friend for this (for Drupal 6 and 7).

The downside is all configuration is done in PHP Classes so you must have a reasonable amount of knowledge about them.

The upside is the documentation. The migrate module comes with an excellent example module that has examples for importing taxonomy, users, nodes + comments, files and roles from a SQL database and XML (it can also import from CSV, JSON and more but is not part of example module)

If you're looking for a nice UI to handle all this, migrate is not for you. You won't find anything else as flexible and full featured though.


Prevent block from caching I have a custom block that reads information from the database. As the user will be filling out a form, refreshing the page and viewing the block it cannot be cached. How do I fix this?

I have tried:

$build['#cache']['max-age'] = 0;

And this did not fix it.

I also tried copying the code from the custom block to the top of the form, so it runs as part of the page, here it doesn't cache. Unfortunately this isn't a solution as I need the block on another page also.

Drupal caches the already rendered block and doesn't check for changes in code, so after changing #cache in the block's render array as shown, you'd still need to use drush or the UI option to force-clear the render cache after changing this.

As an alternative, try deleting the block instance and placing it again.

Since you don't indicate that the form is making changes to the database, it's not clear if there is any cache tag to associate - is it data input or something more like a search form?


How can I render plain text as HTML in a template? I've run into a wall trying to render a SVG image markup code into html from a plain text field.
I'm looking to render the SVG code from a plain text field without overriding the plain text field rendering everywhere else.
plain text format currently converts all HTML tags and <> to &lt; &gt;.
I created a field template and tried both outputting the field content as
{{ item.content.context.value }}

and
{{ item.content|raw }}

both render the value as string wrapping every line with "quotation marks" and converting line-breaks into <br/> tags.
I previously had the field type formatted text, but that also wrapped everything in <pre> tags, even when all tags were allowed. I'd really like to get it working with plain text.
Example of the svg-code the field has to hold in text form:
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
         viewBox="0 0 290 290" enable-background="new 0 0 290 290" xml:space="preserve">
    <g>
        <path fill="none" stroke="#78C681" stroke-width="3" stroke-miterlimit="10" d="M261.1,273.1H28.9c-6.6,0-12-5.4-12-12V28.9
            c0-6.6,5.4-12,12-12h232.1c6.6,0,12,5.4,12,12v232.1C273.1,267.7,267.7,273.1,261.1,273.1z"/>
        <circle fill="none" stroke="#1B435D" stroke-width="2" stroke-miterlimit="10" cx="145.2" cy="166.9" r="62.7"/>
        <line fill="none" stroke="#78C681" stroke-width="3" stroke-miterlimit="10" x1="16.9" y1="60.8" x2="273.1" y2="60.8"/>
        <circle fill="none" stroke="#1B435D" stroke-width="2" stroke-miterlimit="10" cx="178.3" cy="152.3" r="6.8"/>
        <path fill="none" stroke="#1B435D" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" d="M115.1,167.9
            c8.8,0,22.3,3.2,28.4,4.7"/>
        <path fill="none" stroke="#1B435D" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" d="M151.9,216.9
            c0,0,17.2-1.5,29.6-14.8"/>
    </g>
</svg>

A solution by iworkyon from the Drupal community:
field--node--[field name].html.twig:
{% if svg %}
  <div class="my-svg">
    {{ svg|raw }}
  </div>
{% endif %}

MYTHEME.theme:
/**
* Implements hook_preprocess_field().
*/
function MYTHEME_preprocess_field(&$variables, $hook) {
    switch ($variables['element']['#field_name']) {
      case 'field_svg_test':
        $variables['svg'] = $variables['items'][0]['content']['#context']['value'];
        break;
    }
}


How to migrate content edits in Drupal from staging to live environment I have stagging environment where I used to add and update contents first and than move it to live site once the changes passed by the QA.

I can't use the backup and migrate module because of the larger size of the database.

Also can I make the process automatic so that every day I won't need to manually migrate the content from stagging site to live site.

I use readonlymode when migrating my sites, which I daily do to migrate localhost content to remote host.
I use drush's sqlq command to restore which better than BackupRestore module.

For proper migration, you must compare sites/all folder with that of live one. You also need to copy sites/default/files to the live one.

My typical restore goes like as in this Perl script:

chdir ("$home/public_html/$site") or die "Unable to change to site dire=$home/$site\n";

( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =   localtime(time);

$mon++;

$year += 1900;

my $file = "$inputdir/$prefix-sql-dmp-$mday-$mon-$year.sql";

-r "$file.gz" or die "$file.gz does not exists\n";

#compare modules
my $modulesfile="$inputdir/$prefix-all-$mday-$mon-$year.tar.gz";
my $modulesdir="$home/public_html/$site/sites/all";
if( -f $modulesfile)
{
run_cmd("$home/scripts/gij-restore/dircmp.sh $modulesfile $modulesdir");
}
run_cmd ("gunzip $file.gz");

run_cmd ("drush cc all");

run_cmd_ignore ("drush cron");

run_cmd ("drush vset site_readonly 1");

run_cmd ("drush sqlq --file=$file");

run_cmd_ignore ("drush pm-disable --yes devel ");

run_cmd ("drush cc all");

run_cmd_ignore ("drush cron");

run_cmd ("drush vset site_readonly 0");

unlink "$file" or die "Failed to delete $file";

print "Site restore success\n";

sendemail($site,"Restore success!");


How to add a send email action link in views using the same VBO send email action Views Bulk Operations (VBO) has a send email action that sends you to an email form. How can I add a views field to a list of users that creates a link to the same action form that VBO uses to send email, but for just that user row and then pre-populate the recipient field? I believe VBO uses the system_send_email_action_form.

In order to do this with VBO you'll need modify the system_send_email_action_form form (to default its recipient) and add some custom JS (to create click events that automatically submit the VBO form).

An easier alternative here is to use the Views Send module which does nearly the same thing with a slight UI difference; there's a Send Email button at the bottom of the view as opposed to a send email link for each row.


privatemsg and services fully integration Does there exist any module even sandbox or starting point module (not ublished on drupal.org) to help achieve privatemsg crud operations over services module.

There exist a sandbox project pm services clone comand

git clone --branch 7.x-1.x    https://git.drupal.org/sandbox/deminy/2413647.git privatemsg_services

cd privatemsg_services

also  pm services(profile2) but it needs profile2 to be enabled beore


How to write phpUnit tests for hook_form_alter? I have 1 function that is returning cancel form button. This function is in my .module file.

function _cancel_button(array &$form, FormStateInterface &$form_state) {
  // Adding buttons to cancel form.
  $form['actions']['cancel'] = [
    '#type' => 'submit',
    '#value' => t('Cancel'),
    '#access' => TRUE,
    '#submit' => ['redirectcallback'],
    '#limit_validation_errors' => [],
  ];
  return $form;
}

How to write PHPUnit test for this function? Is is possible to write a test for a function which is not enclosed in any class or don't have any namespace?

It is technically possible to write a unit test for this. You'd need to manually require your .module file though.

It might be easier to use a Kernel test, as these will automatically load module files, fire hooks, etc.

MyTest extends KernelTestBase {

  /**
   * Modules to enable.
   */
  public static $modules = ['my_module'];

  /**
   * Test the function.
   */
  public function testCancelButton() {
    // The .module file will already be loaded, so you can call your custom function directly.
    $form = [...];
    _cancel_button($form, ...);
    // Now make assertions about expected changes.


$node->type throwing PHP errors, occasionally I've created some PHP code to get the node type, use it to get a filename, check if there is a banner image existing by that name; if the file doesn't exist, I render the default image.

In the images folder I'd have the following images.

images/content_type.jpg
images/default.jpg
images/careers.jpg

If the content type is careers, and there is an image called careers.jpg, then that image is displayed, but if that image isn't found then default.jpg is displayed.

    $type = $node->type;  // This is line 131.
    $type = preg_replace('/\s+/', '-', $type);
    $type = strtolower($type);

    $base_path_trimmed = $base_path;
    $base_path_trimmed = rtrim($base_path_trimmed, '/');

    $img_url = "$base_path_trimmed/sites/default/files/images/banners/sub-banners/$type.jpg"; //placed in variable so it's rendered out in $image
    $image = $_SERVER['DOCUMENT_ROOT'] . $img_url; //php is weird and checks from the server root rather than web root.

    if (file_exists($image)) {
      print "\n";
    }
    else {
      print "\n";
    }

The code works, except I sometimes get the following errors:

  Notice: Undefined variable: node in include() (line 131 of templates/page.tpl.php).
  Notice: Trying to get property of non-object in include() (line 131 of templates/page.tpl.php).

What can I do to avoid those errors? Is there a better way to write the code I need?

EDIT: Better way is to use the Dynamic Banner Module.

If your site is barfing on

$type = $node->type;

then it more than likely means that $node isn't a real node.  If you are using this in page.tpl.php, then I would guess it is because the code is being called on a non-node page.

BTW, you shouldn't need to place any code in template files.  That is what the preprocess functions are for.  If you need to do things with the page template, then check out template_preprocess_page.


SQL Subqueries in Views I have a View, with its corresponding SQL query. I want a field to be a subquery ( SELECT * FROM TABLE table WHERE ... ) with its corresponding result fields. I don't know if this is allowed, it seems more like a field which is another View in itself, to be called from my View. Is that possible at all?

You requirement can fulfill Views Field View module

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

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


How to get nid and title from a node array use Drupal\node\Entity\Node;

function abc($v) {
  $node = \Drupal\node\Entity\Node::load($v);
  print_r($node);
}

The array structure of $node is as given below

Drupal\node\Entity\Node Object (
[in_preview] =>

[values:protected] => Array
    (

   [nid] => Array
        (
            [x-default] => 166
        )

    [vid] => Array
        (
            [x-default] => 180
        )

    [type] => Array
        (
            [x-default] => sections
        )

    [uuid] => Array
        (
            [x-default] => 7759efc9-cfff-4d58-b392-8d60b9903323
        )

    [langcode] => Array
        (
            [x-default] => en
        )

As mentioned in the comment of @Hudri Node is an object not an array.

In Drupal 8 there are two ways to get the value of a field.

$node->field_name->value
$node->get("field_name")->getValue()

In your case you can get the nid and title like below:

$nid = $node->id();
$title = $node->label();

or

$title = $node->getTitle();

To read about objected-oriented programming conventions In Drupal 8 check this blog article: Drupal 8 API: objected-oriented programming conventions.


xml feed parser from multiple sources, multiple url-source xml importers I can't seem to find a good module that does what my title says. Xpath XML Parser is limited to a single source isn't it?

I needed to be able to import xml feeds from different URLs towards the same target (e.g. mapped to a specific content type). Say, my website will publish contents from different client's websites using an xml specification defined by me. My website then will get all contents by importing all those xml sources towards the same content type so my site will list all contents from different 'sources' effectively. Say real estate listings coming from different real estate agencies/agents...

Has anyone done this before?

To me this seems like an exact use case for Feeds plus Feeds XPath Parser.  It will be possible to map your custom XML spec to various fields and import content from as many sources as you want into nodes of the same content type.  I posted an answer to another question which may give guidance on how to use it.
Feeds:

Import or aggregate data as nodes, users, taxonomy terms or simple database records.

One-off imports and periodic aggregation of content

Import or aggregate RSS/Atom feeds

Import or aggregate CSV files

Import or aggregate OPML files

PubSubHubbub support

Create nodes, users, taxonomy terms or simple database records from import

Extensible to import any other kind of content

Granular mapping of input elements to Drupal content elements

Exportable configurations

Batched import for large files

Feeds XPath Parser:

Feeds XPath Parser is a Feeds plugin for parsing XML and HTML documents. It enables site builders to leverage the power of Feeds to easily import data from complex, external data sources. Each element you wish to extract is setup using configurable mapping queries, saving time for developers who would otherwise have to code complex, specific-use modules. It also enables end-users to build web scrapers and other useful tools within Drupal.


Is there anyway to get more control over when CRON runs? I've just setup some rules using the Rules Scheduler module. Everything is working as expected, except that when a rule is scheduled for 10:30am, it might not run til 11:00am, because that is when CRON runs.

Furthermore, when I go to the CRON settings page, it only allows me to select the intervals which CRON runs at.

Is there anyway to schedule a CRON task, e.g. everyday at 10:30? If is there anyway to be sure that if I set CRON to run at 1 hour intervals, CRON is running on the hour, and not some random time, based off when someone last pressed the run cron button?

I'm running Drupal 7 on a Windows platform is that makes a difference.

You can use "Elysia Cron" or "Cron Control" module to control the cron.

I have not worked on "cron control" module, but I have used "Elysia Cron" module to manage different cron in the site.

Elysia Cron: http://drupal.org/project/elysia_cron
Cron Control: http://drupal.org/project/cron_control


Next/Previous button for nodes within a book I want to have Next and Back buttons for nodes within a book.

What is the easiest way to achieve this?

ok, this can be achieved by overriding of modules\books\book-navigation.tpl file. Copy this file to your Theme and change following:

 <?php if ($has_links): ?>

      <?php if ($prev_url): ?>
        <a href="<?php print $prev_url; ?>" class="page-previous" title="<?php print t('Go to previous page'); ?>"><?php print t('‹ ') . $prev_title; ?>
      <?php endif; ?>
      <?php if ($parent_url): ?>
        <a href="<?php print $parent_url; ?>" class="page-up" title="<?php print t('Go to parent page'); ?>"><?php print t('up'); ?>
      <?php endif; ?>
      <?php if ($next_url): ?>
        <a href="<?php print $next_url; ?>" class="page-next" title="<?php print t('Go to next page'); ?>"><?php print $next_title . t(' ›'); ?>
      <?php endif; ?>

    <?php endif; ?>

to:

<?php if ($has_links): ?>

      <?php if ($prev_url): ?>
        <a href="<?php print $prev_url; ?>" class="page-previous" title="<?php print t('Go to previous page'); ?>"><?php print t('Back') ?>
      <?php endif; ?>
      <?php if ($parent_url): ?>
        <a href="<?php print $parent_url; ?>" class="page-up" title="<?php print t('Go to parent page'); ?>"><?php print t('up'); ?>
      <?php endif; ?>
      <?php if ($next_url): ?>
        <a href="<?php print $next_url; ?>" class="page-next" title="<?php print t('Go to next page'); ?>"><?php print t('Next'); ?>
      <?php endif; ?>

    <?php endif; ?>


What happens when two files with the same name are uploaded? On Monday, I upload dogs.png as my profile picture on my Drupal site.

On Tuesday, I change the image to something else (but keep the name "dogs.png") and upload it as my associate's profile picture.

What will Drupal do to resolve this conflict?

It will rename the second file for you. If dogs.png exists, Drupal will try dogs_0.png, dogs_1.png and so on, until it finds an unused filename.

The behaviour comes from the $replace parameter to file_save_data(), which can be one of the following:

FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with the destination name exists then its database entry will be updated. If no database entry is found then a new one will be created.
FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is unique.
FILE_EXISTS_ERROR - Do nothing and return FALSE.

The default is FILE_EXISTS_RENAME, which is used for managed file form elements like the user profile picture, and file field widgets too.


Trying to edit the breadcrumbs for views using Custom Breadcrumbs module I'm trying to use the custom breadcrumbs module with Drupal 7, and I'm having issues generating a custom breadcrumb - it only seems to want to let me edit nodes/add custom bread crumbs to nodes.

How would I go about adding a custom breadcrumb to a view?

The stable Drupal 7 version of Custom Breadcrumbs is currently in the 1.x branch; support for Views has only been added in the 2.x branch, for which there is no stable release for either version (there's an RC available for Drupal 6 but only a dev version for Drupal 7).

I think your options are:

Try the 7.x-2.x-dev branch and report any problems you find back to the module issue queue
Implement hook_preprocess_views_view() for your view and set the breadcrumb in there programatically (with code similar to the below).
Add custom PHP code to the header of your view (not advised):

$breadcrumb[] = l('Home','<front>');
$breadcrumb[] = l('View Name', 'path/to/view');
drupal_set_breadcrumb($breadcrumb);

A number of other 'hacky' methods that involve overriding the theme_breadcrumb function and making changes based on the path of a View (see this post for some examples).


What Happened To Disqus? I'm using Drupal 7.38 with the Disqus (version 7.x-1.12) module.

Disqus simply fails to load.  No trace of it in the console, elements or sources.

Disqus visibility is set to appear in  block as per /admin/config/services/disqus and block is configured. Its "permissions" are configured properly also.

Disqus was previously working.

Did you add the disqusapi library to /sites/all/libraries (or a similar location)? This happened to my site. Our Disqus comment block stopped loading on existing nodes, and I could not turn on Disqus comments for new nodes.

Then I noticed the message in the Disqus config (/admin/config/services/disqus) that I needed to have the Libraries module installed and api files.

Once I added those files, the Disqus block loaded again.


Change block data with page cache I have enable page cache for anonymous users and no cache for block. There are some random data in cache that change on every page refresh.

Once the page cached by cache_page bin block content is not changing, but it working fine with administrator.

How can I fixed this problem with page cache enable.

For Drupal 7, there is Authcache module. In Drupal 8, you could use Dynamic Page Cache from core.

You could also use some JavaScript. If you have random data to display, you could display them all, hidden by default and use javascript to display one of them each time. Or you could use AJAX, request a URL that will return your new block content, on each page refresh. Disable cache for specific blocks has more information that can help you.

If you have multiple dynamic blocks in your website, my suggestion is to use a module, as it will take you less time to implement it. Writing JavaScript for each dynamic block will take you more time, to implement it and maintain it.


How can i add a depth class to UL in a menu list? I try this code, but i get only the same default depth for all UL tags.

function MYTHEME_preprocess_menu_tree_override(&$variables) {
  $variables['tree_raw'] = $variables['tree'];
}

function MYTHEME_menu_tree($variables) {
  $menu_level = isset($variables['tree_raw']['#depth']) ? $variables['tree_raw']['#depth'] : 1;
  $class = "menu menu-lvl-".$menu_level;
  return '
' . $variables['tree'] . '
';
}

For Drupal 7.

MYTHEME_menu_link(array $variables) {
  global $_current_menu_depth;
  $element = $variables['element'];
  $_current_menu_depth = $element['#original_link']['depth'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

function MYTHEME_menu_tree($variables) {
  global $_current_menu_depth;
  return '
' . $variables['tree'] . '
';
}

NOTE! I noticed this breaks in some cases. I had a three levels deep menu and the second level menu was marked as third.


How do I setup Drupal/Varnish caching so Content Editors don't see browser-cached pages after logging in? I've got a bit of a situation going on with our caching solution and would love some input.

We use a solution of HAProxy -> Varnish -> Apache. HAProxy terminates SSL and sends that to Varnish which then requests from Apache if needed.

We are using Drupal 7, Purge, and Cache Expiration.  We have Cache Expiration set to use external expiration and include the baseurls.  Our sites have "Minimum cache lifetime" set to "none" and "Expiration of cached pages" set to "6h".

The Varnish cache always has the correct versions of the cached pages and those get expired correctly.

If an anonymous user visits a page, say node/123, and then logs in and subsequently navigates back to the same page the browser still serves the browser cached version of the page.  This is the expected behavior from Drupal as I would expect the page to stay cached for an anonymous user.

Our content editors are required to reload the page (F5) and think there is an "error" because they need to perform this in order to see the expected, authenticated, version of their page.

How do other administrators who allow editing on production instances tackle the issue?

I toyed around with the idea of shortening the cache lifetime that comes out of Varnish, but that feels like a band-aid (30s cache vs. 6h).  I also toyed with the idea of removing the cache headers coming out of Varnish, but allowing Varnish to hold the cache for its lifetime.

I'd like to be able to cache responses to keep the load off of our server if at all possible.

Thanks in advance!

See the answer to this question:
https://drupal.stackexchange.com/a/117984/3279

Example usage for the D6 varnish module can seen here:
https://www.drupal.org/node/738420

So, you could do a hook_form_alter in a custom php module for D7 that adds an additional submit handler to your nodes that basically calls the D7 equivalent code to clear the varnish caches for the 1 node path path/aliases in question.


How to make complex taxonomy searches How do I make complex taxonomy searches? Simplifying my drupal database to the following example (number in quotes are the taxonomy numbers assigned by drupal):

Nodes = Blogs, Stories, Questions, Forums

The following are taxonomy dropboxes

Author = A.Tan(1), B.Chua(2), C.Smith(3), D.Perez(4)
Category = Gadgets(5), Food(6), Movies(7), Entertainment(8)

I want to make a complex search for example all Blogs by B.Chua pertaining only to Movies category? I could almost do this with the advance search since it allows checkboxes to search particular nodes and taxonomy however would not accept a blank or asterix as a search word.

You can do that with Views. Create view for nodes, add a filter for these two vocabularies and expose them, so that they can be selected by the user.


Allowing anonymous user based on condition I'm currently working on a custom module with an access form and set permissions for anonymous users.

I'm trying to make it so that when an anonymous user enters the password in the access form, they are logged successfully into 'node/3.'

The trick is, 'node/3' and any other basic page node is blocked for anonymous users via the following code I placed in my .MODULE file.

use Drupal\node\NodeInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
function cookie_authentication_node_access(NodeInterface $node, $op, AccountInterface $account) {
if ($account->isAnonymous() && $node->gettype() == 'page') {
return AccessResult::forbidden()->cachePerPermissions();
}

return AccessResult::neutral();
}

Now, how do I get the anonymous user to access the page only for the condition that the password is entered in the access form?

Here's the code for the access form:

<?php
/**
* @file
* Contains \Drupal\resume\Form\CookieForm.
*/
namespace Drupal\cookie_authentication\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
class CookieForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'cookie_authentication';
  }
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state)       {
     $form['password'] = array(
      '#type' => 'textfield',
      '#title' => t('Access'),
      '#required' => TRUE,
     );

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#button_type' => 'primary',
     );
    return $form;
  }
  /**
   * {@inheritdoc}
   */

    public function validateForm(array &$form, FormStateInterface  $form_state) {
        $values = $form_state->getValue('password');
        //$configValue =  $config->get('access');
        $configValue = \Drupal::config('cookie_authentication.settings')->get('access');
         if ($values != $configValue) {
            $form_state->setErrorByName('password', $this->t('This value is not valid!'));
        }
    }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $password = $form_state->getValue('password');
    setcookie("password", $password );
    drupal_set_message('valid code');
    $response = Url::fromUserInput('/node/3');
    $form_state->setRedirectUrl($response);

}

}

The password is loaded through a config form I built into the back-end...

You can store a value on the session if the password match and then check that value:

$_SESSION['password_match'] = TRUE;

Or even better, as suggested by @4k4 you can do it the D8 way.

CookieForm class:

$session = $this->getRequest()->getSession();
$session->set('password_match', TRUE);

hook:

$password_match = \Drupal::request()->getSession()->get('password_match');


Views Filters Populate + Autocomplete I want to search in one text field on 2 values. I'm using the Views Filters Populare module for this. This works perfectly. But how can I have an autocomplete on this one text field and show both the fields that are searched for?

This is what I have now in my View:

with the same views you can use filters in global variables and this module https://www.drupal.org/project/views_autocomplete_filters you can make this


How to keep Drupal site code in version control in sync with production code when using drush updates on servers? I have 50 D7 sites I support (none are multisite). We do local development for changes to themes and modules tied to new functionality and bug fixes. Once the update works locally, we check that into git and use automation to push changes to our test servers.

Security and core updates tend to be run directly on our test and production sites using  drush upc --security-only

How can I keep our git repo in sync with the state of production code?

I can request a dump of production code and use a difftool to compare that to the latest commit and then apply those updates to the git repo code and commit, but is there a better way to do this?

You really have two options:

Assuming you are deploying code to your test server by cloning your code base from a service like github then you can always go in the reverse direction for security patches. You can patch your test servers (or even Prod, though thats not recommended) directly, commit the patched changes to your local git repo on your test server and then push that commit to your remote repo on github. On your local development server you can now pull from your remote git repo on github and everything is in sync.
Alternatively (and probably less optimal) you can patch your code on your test server directly AND you can simultaneously apply the same patch to your local code base. This way the same changes should be made in both places. This method is DEFINITLY not as good because it makes A LOT of assumptions about how well you are keeping everything in sync, but it can work.


Adding prefix and suffix to a content type field Is there a way to add content to a content type's field in a mechanized way? Say for instance I have a field for how many servings a recipe is going to make but I don't want my user to have to write "Makes" and "Servings." over and over again and risk spelling something wrong.

Is there a way to make it so all she needs is a number field and I can automagically make it say "Makes" [number] "servings."

Perhaps there is a hook or module that I can use?

You can add prefix and suffix in the display settings of the field with the Simple Field Formatter module

Download and enable the module
Go to admin/structure/types/manage/mycontenttype/display
Click on the settings icon for the specific field


Custom Block Class with custom Template, cache issue I need add a custom block in my website, this block must show some users values (from customs fields).

I can show all user variables I want but if a user value change for some reason, I must clear all caches for get the news values from the page where is showed my custom block.

I checked the drupal 8 cache API and try find some example, but I don't find how I do for my variables aren't cached. (or cached but refresh when datas user change)

My code is very simple, I have this hook theme (in my .module) :

function main_menu_theme($existing, $type, $theme, $path)
{
  $theme=array();
  $theme['block__main_menu_quick_stat_block'] = array(
    'base hook' => 'block',
    // 'render element' => 'block', // I tried with and without this line..
  );
  return $theme;
}

This is the build method from my Block Class:

class MainMenuQuickStatBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];

    // Get the currect Drupal User
    $user = _getCurrentUser();

//I tried this...
//  $build['main_menu_quick_stat_block'] = array(
//    '#one' => $user->customfieldone->value,
//    '#two' => $user->customfieldtwo->value,
//  );
//  return $build;

//I tried this...
//    return array(
//      'main_menu_quick_stat_block' => array(
//        '#cache' => array('max-age' => 0),
//        '#one' => $user->customfieldone->value,
//        '#two' => $user->customfieldtwo->value,
//      ),
//    );

//Last try..
    return array(
        '#one' => $user->customfieldone->value,
        '#two' => $user->customfieldtwo->value,
        '#cache' => [
          'max-age' => 0,
          // 'contexts' => ['user',], // I tried this
          // 'contexts' => 'user', // I tried this
        ],
    );
  }
}

For my custom template, I copied the default block.html.twig template from the theme directory.
I can show variables "one" and "two" from the webpage thanks to the custom template. But impossible to configure theses variables for they become uncacheable !

I also try with cache tags but no success..

EDIT 1 (after 4k4 detailed answer !)

This is my last try :
From my custom Block Class :

class MainMenuQuickStatBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];
    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

    //$user = \Drupal::currentUser(); // If I use this way, I get this error in the "'tags' => $user->getCacheTags()," below : "Error: Call to undefined method Drupal\Core\Session\AccountProxy::getCacheTags() in Drupal\main_menu\Plugin\Block\MainMenuQuickStatBlock->build() (line 52 of modules/custom/main_menu/src/Plugin/Block/MainMenuQuickStatBlock.php)."

    $var1 = $user->field_field1->value; //If a log var1, I get a value here ($var1 = 7 by example)
    $var2 = 42; //its a test

    return [
        '#theme' => 'block__main_menu_quick_stat_block',
        '#test' => 42,
        '#var1' => $var1,
        '#cache' => [
          'contexts' => ['user'],
          'tags' => $user->getCacheTags(),
        ],
    ];
  }
}

From my .module file :

...
function main_menu_theme($existing, $type, $theme, $path)
{
  $theme=array();
  $theme['block__main_menu_quick_stat_block'] = array(
    'variables' => [
      'var1' => NULL,
      'test' => NULL,
    ],
  );

  return $theme;
}

I cleared caches (drush cr)

My custom template block is called when I load the page, but variables 'var1' and 'test' are null. Below, I log variables array with "{{ kint() }}" in my custom template :

I'm going to find drupal guide for know why my vars are null...

The problem is not your choice of cache parameters. If you set cache max-age to 0 you don't need any other cache setting to disable the cache.

The problem is how you use the block template. You probably render only the single variables you've added and not the default {{ content }} variable. This is the reason the cache info gets lost.

Better use a custom twig template for the custom variables:

hook_theme() in mymodule.module:

function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'mytemplate' => [
      'variables' => [
        'var1' => NULL,
        'var2' => NULL,
      ],
    ],
  ];
}

build() in block class:

  public function build() {

    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    $var1 = $user->field_field1->value;
    $var2 = $user->field_field2->value;

    return [
      '#theme' => 'mytemplate',
      '#var1' => $var1,
      '#var2' => $var2,
      '#cache' => [
        'contexts' =>  ['user'],
        'tags' => $user->getCacheTags(),
      ],
    ];
  };

mytemplate.html.twig:

Additional user info

Field 1: {{ var1 }}

Field 2: {{ var2 }}

The template mytemplate will be nested inside of the block template, which then, if you change it back to default, can merge the cache data to the block level and page elements on higher levels.


How do I hide specific node fields to users not registerd to that specific node? I am building a site with a course content type. Users can only view some of the course details (such as date, location and description) unless they are registered on the course. Once registered their is certain webforms and file downloads related to the course which they can access too.

A company admin user (sponsor) should be able to access specific courses, and if they have access to a course they can invite people (delegates) to register on the course. Basically each individual course is by invite only.

I'm a little confused as to how to build this. I assume Organic Groups, and/or Entity Registration may be the right direction, but I've never actually used either Module. Does anybody have any suggestions on how I can build this? Which Modules should I use and does anybody have any tutorials or references which may help in this specific area?

You need  to use Field Permissions module, with the help of this module you can do your stuff. Which allows site administrators to set field-level permissions to edit, view and create fields on any entity. With this module you can hide the certain node field to anonymous user.

  Enable field permissions on any entity, not just nodes.
  Role-based field permissions allowing different viewing patterned based on what access the user has.
  Author-level permissions allow viewing and editing of fields based on who the entity owner is.
  Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields
  where this feature is needed.


What is the proper way to create a custom user field programatically? I'm currently working a custom user registration module for a project I'm busy with. I need to add a boolean field which will be attached to user entities. The value will just serve as a flag to check whether a user has answered a CAPTCHA question as a final step of registration. I've been trying to define a boolean field which should have no widget selection dropdown or edit / delete operations within the "Manage fields" section for users.

It seems that the best way to define the field would be during hook_enable or hook_field_schema (inside your .install file), but I'm confused as to what the best practise is.

Also, is there anyway to give the database table a better name when defining your field? I find the table prefix for fields "field_data_xx" pretty confusing if you're defining numerous custom fields.

Thanks in advance :)

Q1: The field should be added in hook_enable() and removed in hook_disable() if you want the field to be removed and then added when you enable/disable the module. However I suggest implementing it in hook_install() and hook_uninstall as that will only remove the field and its data from the user entity when the module is uninstalled as oppose to simply disabled. hook_field_schema is not for these kinds of tasks as it's for defining a database table.

Q2: You'd have to hack your way through the field.module to make these database table name changes. This is really bad practice (VERY VERY) and plus I don't see the point of this, or never even heard anyone attempting this. The database tables are for Drupal and not for human eyes. As such they're in a consistent and systematic naming conventions so the field module as well as other modules that use them can easily extract data.


Custom styles on labels in views? I would like to create custom styling for the label in a field for a table in a view. Is this possible within the view edit page? Or will I have to define a custom CSS class and write the styling in the css pages included in the theme?

CSS in the theme (or in the module that provides the View) is the best way to do this.


Links in second language not working when logged out I have inherited a Drupal web site with a lot of modules installed. Part of these modules have been setup to allow for translation of web site elements between English and French.

The site is configured to use paths prefix (mywebsite.com/fr) to indicate items from another language.

When I am logged in as administrator, I can access mywebsite.com/fr and see the french version of the homepage. When I am logged out, trying to get to the same address just redirects me to the english root (mywebsite.com).

Any ideas on where there may be a setting that would only allow logged in users to see translated content?

After much searching, I have code in the site's theme folder, within template.php, that made a call to the drupal_goto function if the connected user was not logged in, for all page requests where the language is set to french.

A search for $base_url led me to find this. Although now seeing that the redirection function in drupal is drupal_goto, I could have found this a lot quicker with a search for that call.


Alter views exposed filter using any hook function I want to alter an exposed filter of a view to add a new field to the existing filter. I tried the same with hook_views_pre_view() and the new filter field added successfully. But after typing something to that autocomplete field, that field disappears. Means on the first page load, field displaying correctly but when AJAX starts it disappears. Also I tried with other hook functions like hook_views_pre_build and hook_views_pre_execute(). Can any one help me on this? Thanks.

function modulename_views_pre_view(&$view) {
  if ($view->name == 'my_view_name') {
      $view_filters = $view->display_handler->get_option('filters');
      //Add new field
      $view_filters['new_field'] = array(
        'id' => 'new_field',
        ..
        ..
      );

     $view->display_handler->override_option('filters', $view_filters);

  }
}

This will be work by using hook_views_default_views_alter function. This function should be defined in MODULE_NAME/views/MODULE_NAME.views.inc file. Need to include this file on .info file as files[] = views/MODULE_NAME.views.inc.

function MODULE_NAME_views_default_views_alter(&$views) {
        if (array_key_exists('MY_VIEW_NAME', $views)) {
          $options = array(
          0 => 'Blocked',
          1 => 'Active',
          );
          $display = $views['MY_VIEW_NAME']->display['MY_VIEW_PAGE'];
          $display->display_options['filters']['field_status']['id'] = 'field_status';
          $display->display_options['filters']['field_status']['table'] = 'field_data_field_status';
          $display->display_options['filters']['field_status']['field'] = 'field_status';
          $display->display_options['filters']['field_status']['value'] = $options;
          $display->display_options['filters']['field_status']['exposed'] = TRUE;
          $display->display_options['filters']['field_status']['expose']['operator_id'] = 'field_status_value';
          $display->display_options['filters']['field_status']['expose']['label'] = 'Status';
          $display->display_options['filters']['field_status']['expose']['operator'] = 'field_status_value';
          $display->display_options['filters']['field_status']['expose']['identifier'] = 'field_status';
          $views['MY_VIEW_NAME']->display['MY_VIEW_PAGE'] = $display;
          }
    }

Hope this may helpful for anyone who are facing same issue.


Why does Drupal store each custom field in a separated table? I understand that, in order to add functionality to nodes and node types, extra fields must be created in the database.

Now, I don't see why a one-field-one-table schema is used instead of favouring the schema of just a single table for a content type, and then, in that additional table, all the extra fields. What are the adventages of that approach?

I have a site with 1,000+ tables and is being a mess to administer.

Because you can reuse the fields and attach them to more than one content type for example.

You actually get 2 tables for each field: one for storing the current version of the data (field_data_field_MACHINE_NAME), and the other one for storing the "historic" (if revisions are enabled) values (field_revision_field_MACHINE_NAME). Some content types can have enabled revisioning, meaning that shared fields need to be "flexible" enough to follow up with that, but at the same time store the values for content types with disabled revisioning.

If you had everything in one big table for content types (I think D5 did this), it would be a really big mess to manage, especially if you would share fields between entities (e.g. nodes and users).

Few suggestions:

See this answer by Clive for more information.
Inspect this on a clean install just to see how it works. Create 2 content types, add some fields (share some of them) and track what has been changed and how is the data stored in the database. You could probably dig some documentation page, but I think this is the best way to understand the schema.
Reuse the fields whenever you can in order to optimize the database more. Be aware that there might be some limitations (e.g. list options, file uploads, required or not, etc.) that will not let you customize fields for every instance, so you will have to create new ones.

I wrote this fairly quickly, but I hope I managed to explain it.


Showing flagged content to users I have flagged contents in a block.But only admin can see the these flagged contents(contents are product variations).I want to show these contents to all authenticated users and anonymous users.Is it possible?Can you help me to solve this issue.

Sounds like a permission issue, each flag you create has it's own permission settings. Have a look under admin/people/permissions


Narrow down which module is causing a PHP warning All of a sudden a site on my development server has been producing this php notice:

Notice: Use of undefined constant FIELD_BEHAVIOR_DEFAULT - assumed 'FIELD_BEHAVIOR_DEFAULT' in _field_info_prepare_instance() (line 297 of /var/www/mysite/modules/field/field.info.inc).
Notice: Use of undefined constant FIELD_BEHAVIOR_DEFAULT - assumed 'FIELD_BEHAVIOR_DEFAULT' in field_behaviors_widget() (line 458 of /var/www/mysite/modules/field/field.info.inc).

Is there anyway to narrow down which module could be causing this error? I've tried disabling a couple but have had no luck so far. I don't want to just disable the display of the warning as I feel I need to find the root of the issue :)

Has anyone else seen this error before? I suspected it might've been the GMap and Location modules for D7, but I've now removed them and I'm still getting this issue.

Thanks for your help!

FIELD_BEHAVIOR_DEFAULT is defined in the core field.module file, which will always be loaded into the page build if you have the core field module enabled.

If you're getting an error that it's not defined then either the field module isn't being loaded for whatever context you're receiving the error in, or the field.module file has been corrupted/changed.

Try getting the field.module file from a fresh copy of Drupal and replacing it on your site, that might fix the problem. If not, grep your sites/all/modules folder for the string FIELD_BEHAVIOR_DEFAULT. That should help you narrow down the modules that use it, and which ones you should try to disable.


"Did not meet requirements; missing migrations" error In a custom D6->D8 migration module, how does one selectively migrate specific content-types, vocabs and blocks, etc, without receiving the error: 'XXX did not meet requirements. Missing migrations XXX'

I can already selective limit via migrate_prepare_row(), but anytime I do so content related to anything not migrated makes MI throw this error and fail.

Is there any core process plugin that addresses this type of scenario per row?

You don't describe precisely how you're doing your custom migration, but the key to missing requirements on migrations you are omitting is to remove the dependencies. The migration that is complaining will have in its configuration something like

migration_dependencies:
  required:
    - d6_user
    - d6_node_type
    - d6_node_settings
    - d6_filter_format
  optional:
    - d6_field_instance_widget_settings
    - d6_field_formatter_settings
    - d6_upload_field_instance

Simply remove references to migrations which you are not running.


Suddenly I can't use the "Media" file uploader in Full HTML CKeditor edit screen but can do in Filtered HTML edit screen I Use D7, CKeditor v 1.16.7 and Media v 1.5.7, all other modules are up2date and the site itself works fine.

I don't recall any special change at the site that would avoid this module of working, yet suddenly it's upload button was removed from CKeditor's Full HTML palette (img 1) while appearing fine in Filtered HTML palette.

Facts:

The CKeditor "Full HTML" profile's settings seems just fine (img 2).
Permissions are fine (I'm the Admin, img 3).
Rebuilding type information for media, didn't help.

Any ideas?

Solved! For some reason (most probably a bug) the Media module button wasn't added automatically to the Full toolbar even after I check-marked "Plugin for inserting images from Drupal media module" in "Editor appearance" at the desired profile's settings page.
So, What I did was after I check-marked "Plugin for inserting images from Drupal media module" I just went on to add the button manually from "Available buttons" to "Current toolbar" (see img), saved, cleared cache, and Vwalla - it worked again!


Query webform submissions I'm attempting to perform a query on webform submissions so I can display all submissions submitted by a specific user. However I'm not sure how to make this query. I made a guess that webform submissions were nodes themselves and performed a query like this

    $query = \Drupal::entityQuery('node')
        ->condition('type', 'webform');
    $nids = $query->execute();
    die(print_r($nids));

But it produced no results. Is there a way I can perform a query on webform submissions so that I can select all submissions authored by a specific user?

UPDATE: Looking through the webform module, I did see some code querying submissions.

$query = $this->getQuery();
$query->condition('webform_id', $webform->id());
$query->condition('in_draft', FALSE);
$query->range(0, 1);

This is exactly the kind of query I want to perform but when I try to use getQuery() I get

  Call to undefined function Drupal\my_module\my_helper_class\getQuery()

I understand how to start entity queries for nodes like this

 \Drupal::entityQuery('node')

But is there a way to start an entity query without specifying the entity type? Or is there a way to find out what kind of entity type webform queries are?

Webform submissions are content entities, so something like this should work:

$query = \Drupal::entityQuery('webform_submission')
    ->condition('uid', $uid);
$result = $query->execute();


Webform with element that has logged in user's username In my D8 site i have several webforms created.
I would like to have a Webform element that will pull/prepopulate logged in user's username. Is there a way to achieve that from GUI?

The reason i want that element is that from within Webform Submissions i would like to be able to filter per Username of the user who submitted the webform. This way username will be included in submission data.

By default it allows filtering webform submissions per submission data only or administrative notes.

Thanks

You can create a Value element with a token to capture and store the current user's name.

name:
 '#title': 'User Name'
 '#type': value
 '#value': '[current-user:name]'


How to create a list of OG groups with no activity using Views? How can I create a list of OG groups with no activity using Views. For example,  the list of groups where users have not created/tagged any content within last 30 days.

Note: We do not have date field attached to Group content-type, the only date associated with groups is group post date.

/**
 * Implements hook_views_pre_render().
 */
function my_module_views_pre_render(&$view) {
  foreach ($view->result as $key => $row) {
    $node = node_load($row->nid);
    if ($node->changed > (time() - (30 * 24 * 60 * 60))) { // 30 days back in time();
    unset($view->result[$key]);
    }
  }
}


Override an url with hook_menu_alter : problem with the file path In 'mymodule', i try to override a menu url with hook_menu_alter, like this :

global $base_url;

$items['node/%node/delete'] = array(
  'page arguments' => array('myfunction', 1),
  'file' => $base_url .'/'. drupal_get_path('module', 'mymodule') .'/includes/custom_node_delete_confirm.inc',
);

I have an error because the file path is relative and begins with a "/"

Failed opening required
'/http://localhost/mysite/sites/all/modules/mymodule/includes/custom_node_delete_confirm.inc'

and this doesn't work too:

'file' => 'includes/custom_node_delete_confirm.inc'

How can i do this ? Thank You

You can set the file path explicitly:

  file path: The path to the directory containing the file specified in "file". This defaults to the path to the module implementing the hook.

So your code might look like:

$items['node/%node/delete']['page arguments'] = array('myfunction', 1);
$items['node/%node/delete']['file'] = 'includes/custom_node_delete_confirm.inc';
$items['node/%node/delete']['file path'] = drupal_get_path('module', 'mymodule');

Be careful not to completely overwrite an existing router item unless you absolutely need to, in your example you're removing the required access callback/access arguments, and also the title; instead only change the values you need to as in the example above.


how to get the bid ( id from multi-instances of block )? is it possible to get and render the bid from a plugin block class build method ?

class HalPublicationBlock extends BlockBase implements BlockPluginInterface
{

  /**
   * {@inheritdoc}
   */
  public function build()
  {
        //do contain id but not bid
        $config = $this->getConfiguration();
        //$bid=$this->get->?

EDIT : i'd like to pass the bid (or values that will be used by drupal as block css indentifier) to JS object and or twig templates , along with the same bloc instance configuration values

You receive the block id via a form value in the blockSubmit function, so if you save it as configuration, you can use it in the build() function. Seems a bit weird to save the block id as another config value, but otherwise you can't access it. Also note that it is possible to use a block plugin without an actual block entity, see https://drupal.stackexchange.com/a/181458/11500

/**
 * {@inheritdoc}
 */
public function blockSubmit($form, FormStateInterface $form_state) {
  $block_id = $form['id']['#default_value'];
  $this->configuration['block_class'] = $block_id;
}

You should probably add it to the BlockBase::defaultConfiguration() function as well. Because this changes the configuration, you will have to save the blocks manually once (to activate the change).


Feeds with Xpath Parser won't import images using image URL in XML file Importing images into a multi-valued image field using image URLs from an XML file is not working for me. The Xpath Parser debug output shows the multiple image URLs being parsed correctly, but the images don't get imported. No problem with other ordinary fields.

The XML structure is:

<units>
  <unit>
    <unit_details>
      <images>
        <image>
          <uri>
             http://www.example.com/files/content/villa-102-1.jpg
          </uri>
        </image>
        <image>
          <uri>
             http://www.example.com/files/content/villa-102-2.jpg
          </uri>
        </image>
      </images>
    </unit_details>
  </unit>
</units>

The context is: //unit

The Xpath query for the image field is: unit_details/images/image/uri

I played around with the image grabber module for feeds, but it failed also - doesn't seem suited to this task.

Is it possible to import images using the image URL from the XML
file?
Is it possible to import multiple images into a multi-valued image field?

I'm using Feeds version 6.x-1.0-beta12+18-dev, and Feeds Xpath Parser version 6.x-1.12

UPDATE:

I was able to import images using the CSV importer and the image URL, so this appears to be a problem with Xpath Parser.

UPDATE 2:

I'm seeing no errors in the dblog or the server log.  That patch is for D7. The images do not show up in the node display, but the other fields do.

Looks like the "enclosure" error gets thrown if the local file name isn't in the right form, but I just have an external URL.  As I mentioned above, the image with the same URL does get imported using the CSV parser, so it doesn't appear to be a problem with the Feeds module, just the Xpath Parser.

The relevant code in D6 (FeedsParser.inc) is:

    /**
       * @return
       *   A path pointing to a file containing the resource referenced by the
       *   enclosure. This method downloads the resource if it is not local. The
       *   file path must be considered temporary and is only valid for the current
       *   page load.
       *
       * @todo Get file extension from mime_type.
       * @todo This is not concurrency safe.
       */
      public function getFile() {
        if (empty($this->file) && $this->getValue()) {
          // Check if this enclosure contains a local file.
          if (!parse_url($this->getValue(), PHP_URL_SCHEME)) {
            if (file_check_location($this->getValue(), file_directory_path()) || file_check_location($this->getValue(), file_directory_temp())) {
              if (file_exists($this->getValue())) {
                $this->file = $this->getValue();
                return $this->file;
              }
            }
            throw new Exception(t('Invalid enclosure %enclosure', array('%enclosure' => $this->getValue())));
          }
          $filename = basename($this->getValue());
          if (module_exists('transliteration')) {
            require_once drupal_get_path('module', 'transliteration') . '/transliteration.inc';
            $filename = transliteration_clean_filename($filename);
          }
          $dest = file_destination(file_directory_temp() .'/'. $filename, FILE_EXISTS_RENAME);
          if (ini_get('allow_url_fopen')) {
            $this->file = copy($this->getValue(), $dest) ? $dest : 0;
          }
          else {
            $this->file = file_save_data($this->getContent(), $dest);
          }
          if ($this->file === 0) {
            throw new Exception(t('Cannot write content to %dest', array('%dest' => $dest)));
          }
          $this->delete_file = TRUE;
        }
        return $this->file;
      }

}

yes it's possible.
Feeds is buggy sometimes.

Try this patch:
http://drupal.org/node/1482530

Can you give more information about what isn't working? What errors are produced etc.


I broke a view and i'm not sure how to fix it I broke a view by adding the "flagged" relationship to the view, then filtering by the flag_id, then deciding against it and removing the relationship. The filter for flag_id was not removed when the relationship was removed so now I get an error on that view -- "The website encountered an unexpected error. Please try again later.".

The actual logged error is

  Uncaught PHP Exception Exception: "No entity type for field flag_id on
  view frontpage" at
  ".../core/modules/views/src/Plugin/views/HandlerBase.php line 712"

I intended on going into the database to fix this but I feel like that's the nuclear option.

Go to /admin/config/development/configuration/single/export and export the .yml file for that view, manually delete the flag_id filter section, and reimport the .yml file under "Single Item", that should fix it.


How do I redirect to an external URL? Drupal 7 has drupal_goto() that would allow redirecting to an external url.

The change record indicated that ControllerBase::redirect is the method to be called in D8.
https://www.drupal.org/node/2023537

This seems to work with internal drupal URLs but throws an error with external http urls -

[12-Nov-2014 21:00:22 Asia/Kolkata] Uncaught PHP Exception Symfony\Component\Routing\Exception\RouteNotFoundException: "Route "https://www.facebook.com/dialog/oaut....." does not exist." at /Applications/MAMP/htdocs/d8/core/lib/Drupal/Core/Routing/RouteProvider.php line 147

What would be the ideal equivalent of drupal_goto in D8 to redirect to an external URL?

With a route name on a Controller:

use Drupal\Core\Controller\ControllerBase;

class MyControllerClass extends ControllerBase {

  public function foo() {
    //...
    return $this->redirect('user.page');
  }
}

With an absolute URL:

return new RedirectResponse('https://google.com');

On a form RedirectResponse doesn't work, then:

With a route name:

public function submitForm(array &$form, FormStateInterface $form_state) {
  //...

  $form_state->setRedirect('user.page');
}

With an absolute URL:

public function submitForm(array &$form, FormStateInterface $form_state) {
  //...

  $form_state->setResponse(new TrustedRedirectResponse('https://google.com', 302));
  // You can change the response code from 302 to whatever you need
}


Updating core from 8.5.4 to 8.5.6 I'm trying to update Drupal core to lasted version with composer update drupal/core --with-dependencies. I followed the instructions given on Update core via Composer, but Composer claims there is nothing to install or update. It also prints the following message.

  Package "drupal/core" listed for update is not installed. Ignoring.

1,
in file composer.json add

"require": {
"drupal/core": "~8.5"
}

Remove line

"replace": {
    "drupal/core": "^8.5"
}

remote folder vendor
remove file composer.log

alter run

composer update --with-dependencies


Views relatonship with multi value field - and views distinct I have a View that shows a list of Classes (nodes) and the relevant Teachers (Users) on my system. It is designed to show one class per table row and then a comma seperated list of the users who belong to this class.

As my "relationship" in the View is a user reference field (multi valued) then I get a list of Classes and teachers names next to them (as this uses the relationship to find Profile2 fields of First Name, Surname etc). But it causes duplicate nodes. I have tried using Views Distinct but you can see what happens below. I can get rid of the duplicates but it doesn't give any way for me to have a comman seperated list of my rewrote ouput of Users.

In my example there are 3 users referencing "Year 2" but when I try to eliminate the duplicates - it only shows one teacher next to that class. Is there a way around this duplicate, multi valued, relationship issue in Views?

use group-by class so it will show you unique class name with teachers for the class


How to restrict a module to a specific core version? Drupal 8.3 introduced some changes, which broke a custom module; fixing the changes causes the module to break in previous Drupal versions. One way to handle this would be to require Drupal core to above version 8.3+ for this module. However, the following changes to YAML file does not work.

core: '8.3'
core: '8.3.x'

Drupal shows the following incompatibility message.

  This version is not compatible with Drupal 8.x and should be replaced.

The official documentation does not provide useful information for core keyword.

So how should Drupal core version requirement specified in the .info file? If not, is there any other way to specify such requirement?

Using core only supports the major version, but you can add a dependency on the system.module with a specific version.

dependencies:
 - system (>=8.3)

Due to a bug in version parsing, you can only do this with the minor version. You can't specify a patch release like 8.3.1.


Form validator and submit handler is not getting called I've created a Form using my module, which looks like this, then I've created a _validate & _submit handler (please see the linked file above). Then, in my front page, I printed the form using:

$form = drupal_get_form('mymodule_signin');
print render($form);

But when I'm submitting the form, the validate & submit handlers are not getting called, I'm getting redirected back to the front page. However, I created a submit button but when I was clicking it, the form was not getting submitted, so I submitted the form using jQuery's .submit() method to submit the function!

Can anyone help me why the form was not getting submitted first time, and finally when it was submitted (using javascript) the handler was not getting called? Here goes the template file I used to render the form.

PS. I created an entry in the hook_menu() and when I submit form using this page, the form gets submitted (calls validate handler). But it is not calling validate/submit handler when I submit it in my front page. :(

I think you should have an element of type submit in your form function.


Passing Argument from URL in Panel to View Pane or Block I have a page where I want to display all resources for a course grouped by taxonomy term. The courses are organic groups and the resources are materials belonging to those groups. I'm using panels to display the content and I'm overriding view_node for this. I have already created a view pane which lists all the different resource categories, and I'm now trying to list all the resources for a category.

The panel is using the following URL structure:

course/course-name/resources/resource-taxonomy-term

So for instance I have a URL

/course/test-course/resources/transport

I then want to display all resources that belong to the taxonomy term "transport". So I guess the URL argument I want to pass is %4.

I've tried for over a day now trying different methods to pass the URL argument to the view without success. I've tried using a view pane to display the results and also a view block, and explored various methods of passing the argument across without success. It works fine in the view itself, but when I put it in the panel it doesn't work. Can anyone show me how I can do it?

I'm using D7.18, ctools 7.x-1.0-rc1, panels 7.x-3.0 and views 7.x-3.7.

Example scenario:

There is a panel containing View Content Pane.

Panel URL: /panel_url

Example with argument: /panel_url/term_name

With BEF: /panel_url?category=123

How to set up (having existing panel and added Content Pane):

Add Contextual filter to the View.
E.g.: Views contextual filters taxonomy name
Change settings in 'View -> Pane settings -> Argument input' to load the argument 'From panel argument' (e.g. First).

Done.

In addition, if you're using Better Exposed Filters, you could do the following improvements.

To set the current active link based on the argument (if you're using select_as_links):

/**
 * Implements hook_preprocess_[themeFunctionName]().
 */
function foo_preprocess_select_as_links(&$variables) {
  $options = isset($variables['element']['#options']) ? array_change_key_case(array_flip($variables['element']['#options']), CASE_LOWER) : array();
  $selected = end((arg()));
  if (array_key_exists($selected, $options)) {
    $variables['element']['#value'] = $options[$selected];
  }
}

To set the current active link based on the argument (if you're using select):

/**
 * Implements hook_preprocess_[themeFunctionName]().
 */
function foo_preprocess_select(&$variables) {
  switch (arg(0)) {
    case 'panel_url':
      if (@$variables['element']['#name'] == 'category') {
        $options = isset($variables['element']['#options']) ? array_change_key_case(array_flip($variables['element']['#options']), CASE_LOWER) : array();
        $selected = end((arg()));
        if (array_key_exists($selected, $options)) {
          if ($variables['element']['#value'] <> $options[$selected]) {
            $variables['element']['#value'] = $options[$selected];
          } else {
            // drupal_goto('panel_url');
          }
        }
      }
    break;
  }
}

To make the links SEO friendly, you can try something like:

/**
 * Implements hook_url_inbound_alter().
 */
function foo_url_outbound_alter(&$path, &$options, $original_path){
  if (arg(0) == 'panel_url') {
    // Convert URL like: /panel_url?category=29 into /panel_url/term_name (SEO friendly)
    $path_info = parse_url($path);
    switch (@$path_info['path']) {
      case 'panel_url/term_name':
      case 'panel_url/term_name2':
        $path = 'panel_url/all'; // Convert loopy urls into base url
    }
    if (strpos($path, '?category=') !== FALSE) { // Convert term id into human name
      list(, $tid) = explode('=', current(explode('&', $path_info['query']))); // get tid from URL
      $term_name = strtolower(taxonomy_term_load((int)$tid)->name);
      $path = '/panel_url' . '/' . $term_name; // See also: $path_info['path']
    }
  }
}


how to setup blocks that differentiate 'node edit' case from 'node add' case in MULTISTEP forms Im using Drupal 6 and the multistep module :

I need to display informations in a block apart when my users wether add or edit some of the available multistep forms :

. there's a block that shows up with an EDIT title when EDITING an existing node with information within it for this case :

only shows up when :
node/*/edit* page

. there's a block that shows up with a CREATE title when ADDING a node :

only shows up when :
node/add/multistep-content-A*
node/add/multistep-content-B*
node/*/edit*

node//edit is necessary for ADDING since when the user finishes the first step of the form, the node is saved and the link which was node/add/m-c-A turns into node/nid/edit.

in both block I use a bit of php ( url arg(), $node) to check content type, to retrieve node info if exists, to decide wether show info for ADDING cases or for EDITING cases. (as there's nothing to show, the entire block DIV does not show up)

I would need to recognize the ADDING case after step 2 of the form...
when the node is created but when the progress bar is lesser than 100%.

in other words, to retrieve the 'completion status' argument from the multistep module, the one that tells the progress bar if the form is completed or not.

it appears it's not in the $node array.. ?

EDIT : found a trick, see comment 2.

I dont know how to retrieve the multistep completion state from a block but there's a simple way, by testing the published status (not published ? not complete ADD/PENDING - published ? complete EDIT)

in admin/settings/multistep :
select Publishing > at node completion

in the ADD block that must be displayed when adding a multistep node :
only display block on the pages below :

node/add/multistep-content-A*
node/add/multistep-content-B*
node/*/edit*

in the ADD block body :

Title : add

<?php
$show = FALSE ;
if ( arg(0) == 'node' && arg(1) == 'add' ) {
  if (in_array(arg(2), array( "multistep-content-A", "multistep-content-B" ))) {
    $show = TRUE ;
    $node = False ;
  }
}
elseif ( arg(0) == 'node' && is_numeric(arg(1)) ) {
  $node = node_load(arg(1));
  if (in_array($node->type, array( "multistep-content-A", "multistep-content-B" )) && $node->status == 0) {
    $show = TRUE ;
  }
}
if ($show) {
  if ($node) print 'id : '.$node->nid . '' ;
  print "

some info about creating this node.

be sure to complete every step blah blah the italic ones

" ;
}
?>

in the EDIT block :

Title : modify

node/*/edit*

body :

<?php
if ( arg(0) == 'node' && is_numeric(arg(1)) ) {
  $node = node_load(arg(1));
  if (in_array($node->type, array( "multistep-content-A", "multistep-content-B" )) && $node->status == 1) {
    print 'id fiche : '.$node->nid . '' ;
    print "

some info about editing an existing node.

browse directly to the steps you need to modify by using the link below.

" ;
  }
}
?>

there might be a way to only have one block, that could change its title itself, I didn't investigate.


Taxonomy Term Reference Fields Don't Get Created on Nodes During Migration I have followed the steps shown here to create/run the migration.  Everything seems to migrate correctly except the Taxonomy Term Reference fields never get added to the nodes.  The taxonomies and vocabularies do get created.

I'm thinking that those fields should have been created in d6_field_instance so here is my migrate_plus.migration.upgrade_d6_field_instance.yml.

uuid: 6e1fd6ac-1ec4-4631-93d1-753068fdc667
langcode: en
status: true
dependencies: {  }
id: upgrade_d6_field_instance
migration_tags:
  - 'Drupal 6'
migration_group: migrate_drupal_6
label: 'Field instance configuration'
source:
  plugin: d6_field_instance
  constants:
    entity_type: node
process:
  field_type_exists:
    -
      plugin: migration
      migration: upgrade_d6_field
      source:
        - field_name
    -
      plugin: extract
      index:
        - 1
    -
      plugin: skip_on_empty
      method: row
  entity_type: constants/entity_type
  field_name: field_name
  bundle:
    -
      plugin: migration
      migration: upgrade_d6_node_type
      source: type_name
    -
      plugin: skip_on_empty
      method: row
  label: label
  description: description
  required: required
  status: active
  settings:
    plugin: d6_field_field_settings
    source:
      - widget_type
      - widget_settings
      - global_settings
  default_value_callback: ''
  default_value:
    plugin: d6_field_instance_defaults
    source:
      - widget_type
      - widget_settings
destination:
  plugin: 'entity:field_config'
migration_dependencies:
  required:
    - upgrade_d6_node_type
    - upgrade_d6_field
  optional:
    - upgrade_d6_field
    - upgrade_d6_node_type

Any idea what it can point me where in code to look.

The problem wasn't in migrate_plus.migration.upgrade_d6_field_instance.yml but instead the problems were in  migrate_plus.migration.upgrade_d6_field.ym and migrate_plus.migration.upgrade_d6_field_instance_widget_settings.yml.  Also in the term yml files I had to update the field name to include field_ in the file name.

I documented how I was debugging and what I was changing here.


Exclude certain webform field to be saved in Database Is there a way we can exclude certain webform field to be saved in Database. Don't want to exclude from email data.

This feature is currently not supported by the Webform module for Drupal 8. You would have to write custom code using hook_webform_submission_presave() to remove unwanted element data.


How to theme simplenews newsletters in D7? I'm looking for something like a walk-through.  (The guide here, http://drupal.org/node/268404, was apparently written before the D6 rewrite).

The reason I'm after this is that when I use the default simplenews newsletter format, and enter for the subject "test" and for the body "test content" my resulting emails look like this:

-------- TES
-----------------------------------------------------------------
Test content**myReport taxonomy**
**myURL**

-- Unsubscribe from this newsletter:
**myUnsubscribeURL**

(The contents between the ** are correct, I've left them out for privacy).  But you can see the issues are things like:

The "t" at the end of "test," the last letter of the header, is left off for some reason.
I'm not sure where the hyphens are coming from, or how to modify that formatting decision. I'd like to eliminate the hyphens both before the heading, and between the heading and the body.
The body of the email abuts the name of the report taxonomy without space or break.
The body of the email comes before the name of the report taxonomy, I'd rather reverse the order.

Can anyone point me to a simple guide to alleviate at least these four problems?  Greater customizability would be helpful, but I need to address these for a minimum viable newsletter before getting fancy.

This happens because this is the default HTML to Plaintext conversion that Drupal is applying to all mails.

If you don't want this, either adjust the templates (you can find them in the theme folder, just copy to your theme and start adjusting it) to avoid HTML or enable a module like Mime Mail that allows to send HTML formatted mails.

No idea why the title is cut off.


How to store field data in a file instead of the db? So far, I found two decent options for storing field in a file:

using node hooks to store data in a filefield, and process it on node view
theoretically, the best would be to use file storage as a backend, but is there a module for field file storage instead of field sql storage?

My use case is a field that does not change, but mysql backup is very slow because there are 600 000 nodes with it. I also do not need to query this field, just display it. With file storage I can do incremental backup which is lightyears more efficient.

Your best bet's going to be using the MongoDB module, I think ... Here is a quote about it (from the module's project page):

... is a collection of several modules which allow sites to store different types of Drupal data in MongoDB.
Views integration provided by EntityFieldQuery Views Backend.