Remove import instance from list using Migrate Tools module I'm trying to remove an rss reference of a migration. Once I put the yaml code into the Migrate module in the drupal admin interface, it creates a reference to that yaml code, but there is no one in the UI that I can see the reference. The Migrate Tools module gives me access to drush commands, but none of which could remove a reference.

Does anyone know how to delete a reference to an import?  I can see references through the command line using $ drush ms

I searched but could only find using this, but it doesn't work.

$ drush php

>>> Drupal::configFactory()->getEditable('migrate_plus.migration.my_rss_importer')->delete();

Here is the list of imports from the CLI I am trying to remove.  Just for reference "migrate_plus" mentioned in the code above is another module that compliments the migrate module.

Group: Default (default)      Status  Total  Imported  Unprocessed  Last imported
 berkeley_news_rss_importer_1  Idle    20     20        0            2017-12-09 23:08:36
 berkeley_news_rss_importer_2  Idle    20     20        0            2017-12-09 23:12:34
 berkeley_news_rss_importer_3  Idle    20     20        0            2017-12-09 23:14:03
 berkeley_news_rss_importer_4  Idle    20     20        0            2017-12-09 23:20:04
 berkeley_news_rss_importer_5  Idle    20     20        0            2017-12-09 23:33:17
 berkeley_news_rss_importer_6  Idle    20     20        0            2017-12-09 23:42:26
 berkeley_news_rss_importer_7  Idle    20     0         0            2017-12-10 00:11:17
 berkeley_news_rss_importer_8  Idle    20     20        0            2017-12-11 09:46:45
 berkeley_news_rss_importer_9  Idle    20     0         20

So you want to get rid of the migrations so that they don't appear in the drush ms output? Do this:

Removing imported content

Upon reading your question the second time, I thought you might even be asking "How to remove the content which is imported already?". If that is your question, then try drush migrate-rollback or drush mr for short. See documentation with drush mr --help.

Deleting the migrations

If you are using configuration management, then delete the relevant config YML files from the config sync directory and do drush cim. There should be files named migrate_plus.migration.MIGRATION_ID. It will ask for confirmation and if you say y, the relevant migrations will be deleted.
If you are not using configuration management, do drush config-list. Now, for every migration you want to delete, search for the name of the migration in the output of the config list and do a config-delete for it. Example: drush cdel migrate_plus.migration.MIGRATION_ID Consider using config management in the long run.

Deleting migration mappings

The migrate module might have created some mapping tables in the database to track your migrations. To delete these tables (I assume you know what you're doing), delete the mapping and messages tables for the migration. Example: DROP TABLE IF EXISTS migrate_map_MIGRATION_ID, migrate_messages_MIGRATION_ID. After you do this, you will never be able to do rollback.

Hope it helps.


Filter date from current date to upcoming 7 days? I have a week type calendar view. It currently displays form SUN to SAT of the current week.

But I need to display it starting from current date to current date + 7 days

How can I achieve this?.  I am using Calendar Module and created a view using it.

My view is displayed only if I add a contextual filter. With default value as current date. This adds a filter criteria from dates starting from the start of the week and end of the week.

In Views filters find your date field.
Now, in filter settings select "is between".
Choose "Enter a relative date" and enter "Now" in the first one and "+7 days" in the second field.


Reference Live Files with Built-In Server I use the built in php server most often when developing locally.

drupal server

Is there any tweak I could make locally to have all my assets referenced on the live site? When I ran apache locally I use to put this in the vhost file.

<IfModule mod_rewrite.c>
  RewriteEngine on
  rewriteCond %{DOCUMENT_ROOT}/sites/%1/files/%2 -f
  rewriteRule ^(.*)$ $1 [QSA,L]
  # Otherwise, send anything else that's in the files directory to the
  # production server.
  rewriteCond %{REQUEST_URI} ^/sites/[^\/]*/files/.*$
  rewriteCond %{REQUEST_URI} !^/sites/[^\/]*/files/css/.*$
  rewriteCond %{REQUEST_URI} !^/sites/[^\/]*/files/js/.*$
  rewriteCond %{REQUEST_FILENAME} !-f
  rewriteCond %{REQUEST_FILENAME} !-d
  rewriteRule ^(.*)$ http://www.livesite.com$1 [QSA,L]
</IfModule>

But now that I'm using the built in server, I can't do that. I was wondering if there may be another way? Preferably without a module that would affect my Drupal site. I just want this as a local modification.

If I understand this correctly, you can just use the Stage File Proxy module. Configure it to point at your production site. It has more configuration associated to it instead of just rewrite rules (which will be overwritten the next time you update core anyway).


hook_nodeapi() is great on nodes, but what can I use on non-node pages? I'm building a module that needs to do stuff wherever the user is browsing, but I used hook_nodeapi(), which is ordinarily great but it is not coping with non-node pages (such as views, and user profile pages). Does anyone have any idea on which hook should I run in such circumstances?

You have three options:

hook_init() This hook is not run on cached pages - though CSS or JS added this way will be present on a cached page.
hook_boot() Only use this hook if your code must run even for cached page views.
hook_exit() This hook is run at the end of each page request. It is often used for page logging and printing out debugging information. Only use this hook if your code must run even for cached page views.

Performancewise, you will want to avoid hook_boot() and hook_exit(), since they will run regardless of caching. Having one module that implements those hooks brings the familiar warning on the performance page, "The following enabled modules are incompatible with aggressive mode caching and will not function properly: …"

If all you need to do, is add some Javascript, static HTML, or CSS, hook_init() is the best option: the JavaScript and CSS you add will be added to the cache and be present.

If, however, you need to run actual PHP that is not needed for the rest of the request, e.g. to write a record in a database, or log a line to some file, then hook_exit() is the best option: it will only be called after the page is already served.

If you need to run some setup: e.g. establish a connection with a service, perform access-check and such, then hook_exit() is the best option.


Opposite result views with comparison I'm trying to achieve this...

A Views that shows as result the names of people who do not appear in list of published nodes of a content type.
(List of people who will not attend an event...)

Configuration:

Content Type Event:
Person field, supports adding more than one (multivalue), using autocomplete.
This field is of the entity reference type and displays the list of possible names obtained from the result of a view.

Assuming that the list of persons is total A B C and D.

I create 1 node of event type
And I included people A and B.

The result of the views should be...
People C and D.

Is this achievable?

Previous setup:
Create a new computed field for the content type where you want to work:
Extract the names from the multivalue field (entity referenced field)

foreach ($entity->field_campos as $field) {
}
foreach ($entity->field_campos as $field) {
}
foreach ($field as $index => $valores) {
$terminos[] = $valores['value'];
}
$item2 = field_collection_item_load_multiple($terminos, $reset = FALSE);

$referenced_titles = array();
foreach ($item2 as $indice => $values) {
  $referenced_node = node_load($values->field_nombre_2['und'][0]['target_id']);
$entity_field[]['value'] = $referenced_node->title;
}

Now that every node from this content type has a special field for extracting the values in a more "flat" way we can compare two views.
The first with the name list (usually partial) and the second, a views containing the full name list.

<?php
$result = views_get_view_result('calendari_intern', 'nombres');
$result2 = views_get_view_result('nom_expedients', 'entityreference_1');

First load both arrays. The first one, is the view result with partial name list. The second, is the view of the full name list.

Extract and create a new array saving only the names from the arrays:

foreach ($result2 as $index => $val) {
$expedient[] = $val->node_title;
}

Do the same in the other one:

foreach ($result as $index => $values) {
$entidades[] = $values->_field_data[nid][entity];
}
foreach ($entidades as $indice => $valores) {
if ($valores->field_nombres[und] !=NULL)
$casi[] = $valores->field_nombres[und];
}
foreach ($casi as $indice2 => $valores2) {
 foreach ($valores2 as $indice3 => $valores3) {
if ($valores3["value"] != NULL) {
$misnombres[] = $valores3["value"];
}
}
}

Then compare the arrays with array_diff function.

$diferencia = array_diff($expedient, $misnombres);
echo '<pre>';
print_r ($diferencia);
echo  '</pre>';
?>


How to put a custom login menu in a page? I'm totally new to Drupal and I'm using v.6.xx.

I've managed to remove the "login" menu via Admin panel.

Now I'd like to create a custom "page" (= no menu) with a customized login form, and once authentified, show a menu with some options and the "disconnect" option.

What is the best way to achieve this?

Thank you very much

ok your question has several parts:

(The standard login form can be accessed through a block, or going to the /user path while logged out)

Custom login form:

http://picxelplay.com/blog/theming-drupal-6-registration-login-and-request-new-password-pages-not-just-forms
http://blog.aphexcreations.net/2009/04/theming-drupal-user-login-form.html
http://drupal.org/node/154236 (outdated)

Custom 'menu':

Create a block that has a link to /logout, going to that path will automatically log out your users. Make sure that the block visibility is only for authenticated users.
Add any other links or options you want.


how can I make date fields come out in other languages in webform with drupal 7 using drupal 7 , and Webform 7.x-3.18 + 3-dev
I need my date field to come out in spanish, mes/dia/ano

but it keeps on coming out with month/day/year

How can I fix this?
thanks

fixed, I was logged in as an admin and had admin language set to english


Do not show errors including database error to users in D7 I have disabled displaying errors to the user in my D7 website. See below the screenshot of the configuration-

However, I (without admin login) still see a database related error such as following-

How do I disable the above error display to a normal user (but making sure admin can see)? It would be better if these errors can be logged but not displayed to a normal user. By saying a normal user, I am referring to all non-logged users.

You should be able to add the following to your settings.php to hide all errors (It will mean the admin screen you mentioned will no longer be used so any changes to this setting will need to be done via settings.php

$conf['error_level'] = ERROR_REPORTING_HIDE;


How can I remove allowed values of a list field? I set up a List (Text) select list field in a paragraph bundle. I set some values to test. I want to remove them (so I can populate them programmatically) and I deleted the content using the fields, but I still get this message.

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

These values are not used. I did use them to test, but I deleted them after testing.

How can I remove those values?

Have you got revisioning on for your content types? If so then those revisions will still be using the paragraph. You'll need to delete the revisions too before you can make the change


Customise entity reference autocomplete How do I override the look up on an entity reference autocomplete field? I would like to limit the look up to nodes of a certain type that have been created by the user that is creating the current node.

The Entity Reference module integrates with the Views module in a few ways.  One of these is a new display called Entity Reference.

Create a view, and filter it to your needs.  Then, add a new Entity Reference display.  Configure this.

Then, on your content type(s), edit the entity reference field.  Make sure you are using the AutoComplete widget.  You should see a fieldset called Entity Selection.  Change this from "Simple (with optional filter by bundle)" to "Views: Filter by an entity reference view".  You should then see a dropdown appear which will have all of the views you have created that have Entity Reference displays.  Pick your view and save.

Keep in mind, though, that views with large datasets can cause dramatic performance problems with autocomplete fields.


How to create paragraph of particular type using JSONAPI? I am able to GET the data using endpoint "site_url/jsonapi/paragraph/text". But I am not able to create a new paragraph of type text. Its always giving me error "403 forbidden". I have tried all drupal permissions also i am using simple oauth and i am using admin token to POST.

Endpont :- site_url/jsonapi/paragraph/text
Request Type :- POST
Post Body :- {

"data": {
    "type": "paragraph--text",
    "attributes": {
        "field_text": {
            "value": "
ദുബായ് ∙ സാമ്പത്തിക അച്ചടക്കമില്ലാത്തവർക്കു കുരുക്കായി ക്രെഡിറ്റ് കാർഡുകൾ. കൃത്യമായി പണം തിരച്ചടയ്ക്കാതെ കുടിശിക പെരുകി കുടുക്കിലാകുന്നവരിൽ മലയാളികളുമേറെ. ബാധ്യത കൂടി ചിലർ വിട്ടുവീഴ്ചയ്ക്കായി ബാങ്കിനെ സമീപിക്കുമ്പോൾ മറ്റു ചിലർ രാജ്യത്തുനിന്നു മുങ്ങും. ഒരു കാർഡിന്റെ ബാധ്യത തീർക്കാൻ മറ്റൊരു ബാങ്കിൽ നിന്നുകൂടി ക്രെഡിറ്റ് കാർഡ് എടുത്ത് രണ്ടും തിരിച്ചടയ്ക്കാത്തവരുമുണ്ട്.
\r\n",
            "format": "basic_html",
            "processed": "
ദുബായ് ∙ സാമ്പത്തിക അച്ചടക്കമില്ലാത്തവർക്കു കുരുക്കായി ക്രെഡിറ്റ് കാർഡുകൾ. കൃത്യമായി പണം തിരച്ചടയ്ക്കാതെ കുടിശിക പെരുകി കുടുക്കിലാകുന്നവരിൽ മലയാളികളുമേറെ. ബാധ്യത കൂടി ചിലർ വിട്ടുവീഴ്ചയ്ക്കായി ബാങ്കിനെ സമീപിക്കുമ്പോൾ മറ്റു ചിലർ രാജ്യത്തുനിന്നു മുങ്ങും. ഒരു കാർഡിന്റെ ബാധ്യത തീർക്കാൻ മറ്റൊരു ബാങ്കിൽ നിന്നുകൂടി ക്രെഡിറ്റ് കാർഡ് എടുത്ത് രണ്ടും തിരിച്ചടയ്ക്കാത്തവരുമുണ്ട്.
"
        }
    },
    "relationships": {
        "paragraph_type": {
            "data": {
                "type": "paragraphs_type--paragraphs_type",
                "id": "6692c53b-f2f3-4a52-a18f-e59d94be3c88"
            }
        }
    }
}
}

This is always giving me 403 forbidden error. Am i doing anything wrong ?

Issue was I didn't enable the "Paragraph Type Permission" module. Install it and go to drupal permissions.


Create a new user from an entry submitted with the module "webform" i'm using the module webform  so that user can ask for the credentials to login to the site. I need to add a button to the the "view" of each submission so that the user that it's viewing that submission can create a user.

Do i have to modify the code of the module to achive this or should i write my own module? If i write my own module what hooks should i implement to add the button, the logic for the button to be present only if i didn't create a user, and the custom action for that button?

I am also looking for a similar solution and would like to reuse an existing one.
To assign a role on registration I would try some of existing modules.
Let me summarize what is available:

Auto Assign Role (D7, D6, D5)
Registration_Role (D5, D6)

To allow a user to choose a role on registration

User-Selectable Roles (D5, D6)

To provide a role using a key during registration

Registration Codes (D7, D6)

Sold Memberships

Ubercart (D7, D6)

Join role with a password

Join role with password (D7, D6, D5)

Apply for role

Apply for role (D7, D6)

Webform register

Webform register (see Open Issues for details)

See also integration Webform and registration module.


How to get child terms based on parent terms between two different taxonomies I have created two vocabulary

Program
Topics

I want to load the topics based on the program selection.

It looks like category and subcategory.

I created some program like java, .net, PHP
and I created some topics like session (php), inheritance(java), cookie(php).

So now I want to list all the topics which are coming under a particular program.

Can you tell me which  drupal function used to get all the terms under parent terms.?

Note: taxonomy_get_children not working because I am using two vocabularies

You'll need to load your content's term references and then load those term entities so you can follow your chain of taxonomy terms. There's many ways to do that; taxonomy_term_load_multiple() is one such function.

$tids = array();

// @TODO: Use the $nid that corresponds with your node
// @TODO: Replace field_program & field_topic with your taxonomy ref field name
$node = node_load($nid);
foreach ($node->field_programs[LANGUAGE_NONE] as $term) {
  $tids[] = $term['tid'];
}
$programs = taxonomy_term_load_multiple($tids);

// @TODO: Iterate over $programs and retrieve
// topic tid references from $program->field_topic[LANGUAGE_NONE]


Filter nodes by currently logged-in user I want a view which shows nodes authored by the currently logged-in user. I can't figure out how to do this in Drupal 7.

just add a view for all your nodes. Then add a "relationship" for "Content: Author".
Now add a "contextual filter" for the field "user: uid" with a default argument for "userid of logged in user" to filter the view.


How can I use the OpenLayers module to draw a route between nodes? I have some nodes; I need to build a route using the location assigned to them, and I want to draw it on a map. How can I do that?

OSM Route looks like it will do exactly what you need.


Cannot disable or replace logo I set up a subtheme of Bartik in Drupal 7. I also set up the private file system. I was styling everything and when I went to upload a logo, the logo broke. Now the logo url is private://logo_0.png. I cannot remove the logo, disable it via the checkbox, or set it back to default.

I tried some of suggestions from around the net such as using [theme]_preprocess_node. I also tried using a default bartik "template.php" file. (I renamed all the prefixes in it to match my theme name.)

Nothing seems to work and this is the weirdest bug I've EVER encountered in Drupal. Anyone have some suggestions or a push in the right direction to try and fix this?

I need to disable the Bartik theme completely to make the sub-theme work.


Where is the "Generate automatic URL alias" setting stored? I have about a 100 nodes where I need to manually change the url alias in the url_alias table. I want to make sure the "Generate automatic URL alias" setting is disabled for those nodes so the url doesn't change when a user changes the title.

I was under the impression the "Generate automatic URL alias" setting would be saved in the database for each node. That's not the case.

Instead I just had to change the pathauto setting from "Create a new alias. Delete the old alias."   to "Do nothing. Leave the old alias intact."  (credits)


How to resolve my error in bootstrap.inc? I use Drupal 7.38 and I have taken the backup from server side and added in my local server. Then the following error showns up:

  Fatal error: require_once(): Failed opening required

  'D:\xampp\htdocs\kaya/sites/all/modules/commerce_invoice_receipt/commerce_invoice_receipt.admin.inc'

  (include_path='../lib;D:\xampp\htdocs\kaya\sites\all\modules\custom\commerce_citrus\lib;.;D:\xampp\php\PEAR')
  in D:\xampp\htdocs\kaya\includes\bootstrap.inc on line 3186

How can I resolve this error?

The file

  D:\xampp\htdocs\kaya/sites/all/modules/commerce_invoice_receipt/commerce_invoice_receipt.admin.inc

Is missing; the Commerce Invoice Receipt module is installed on your site, so the file needs to exist.

If you've lost the file(s) somehow, just download the module again and put it back in place.

If you've removed it on purpose, but without uninstalling the module, follow the above first, then disable and uninstall it. Then you can remove the files safely.


How can I make Private Messages in Drupal 7 with user user pictures like in Facebook? There are many people who want to see their Private Message module in Drupal to look like Facebook - i.e. with user pictures.  Pictures make messages more "personal" and "closer" than e-mails.
I made it work in D5 and D6 by putting functions into template.php, but for D7 I can't find any such snippet that would work for D7.

I've written more about this here http://drupal.org/node/1549540  There's already much of the snippet there, but the DB query returns an error.

Can someone please help write a lasting solution for drupal user in D7?

that's a great idea, I would love to see that too. Wouldn't it be easier replacing the default page with a view? Then you can style it any way you want. The "checkboxes" and actions could be done with VBO.


Create a term reference with a select list selecting one at a time I have a couple term reference fields, one of which allows unlimited values, and one of which allows 4 values.  I'm using Simple Hierarchichal Select as the widget for the unlimited one, and it lets the user select a first value, and then click 'add another item' if they need more.

If I set the other value to a simple hierarchical select widget, it shows 4 rows with no Add another button.  This makes sense, but encourages the wrong behavior for this case -- I'd prefer the user select only one value, but if they need to they can add up to 4.  Having 4 rows from the beginning encourages them to add 4.

I would slightly prefer to use a select list widget for this limited field, but I don't feel confident that users are comfortable with the ctrl-click to select multiple items operation, so I'd prefer a dropdown allowing them to select one at a time, with an add more button.  SHS would be fine too, if I could get it to show the 'add another another item' instead of showing 4 rows from the beginning.

Is either of those operations possible?  Basically I want some kind fo dropdown widget, that allows users to select one value, and require them to click add another item, to add more, up to 4.

You can do it using Field Collection module

Once enabled, go to your content type and add a new field of Type: Field Collection and set to 4 values.

Then go to /admin/structure/field-collections and click on manage fields and add your select list field here and set value to 1.

Result:

If you don't want to allow users to set the same value, then you will need to use jQuery to hide value "X" in the 2nd drop down if the 1st drop down is set to value "X"


When editing a node, some markup disappears I'm using Drupal 7 and my page loads and looks fine when I add a new node and insert HTML markup. When I edit the page, some of the markup either disappears or it's replaced.
For example, if I add
, the node saves and it's displayed fine. When I edit the node,
 is replaced by
. If I add ,  is replaced by
.
Do you know why this would happen? How can I fix it?

I have the same issue, and this is caused by the WYSIWYG editor: When you try to edit a node created with a input format with WYSIWYG enabled, the HTML markup will be changed by the editor.
To solve it, you have two options.

Disable the WYSIWYG editor by default, unselecting the checkbox as shown in the screenshot.

Create a node using an input format that doesn't use the WYSIWYG editor (for example Full HTML, or Filtered HTML). If the Full HTML format is already associated with a WYSIWYG profile, try to create a custom format from /admin/config/content/formats, and use it to create new nodes. Remember to not associate a WYSIWYG profile.


Custom Content Entity type - allow fields to be managed I've created a custom content entity type in Drupal 8. I've tied it in with the Field UI so it can be fielded, and I added some fields in the entity definition using BaseFieldDefinition.

One of the fields I added was this:

$fields['message'] = BaseFieldDefinition::create('text_long')
  ->setLabel(t('Message'))
  ->setDescription(t('The message to be shown'))
  ->setTranslatable(FALSE)
  ->setRevisionable(FALSE)
  ->setDisplayOptions('view', array(
    'label' => 'hidden',
    'type' => 'text_default',
    'weight' => 0,
  ))
  ->setDisplayConfigurable('view', TRUE)
  ->setDisplayOptions('form', array(
    'type' => 'text_textfield',
    'weight' => 0,
  ))
  ->setDisplayConfigurable('form', TRUE);

I want to set a default Text Format for this field, however I'm not sure how to do so. I don't know if I can do it in the code above, but I'm thinking that if I could edit the field settings on the 'Manage Fields' tab, I could do it there. However, I can't figure out how to get my field to show up on that page. It shows up on the 'Manage Form' and 'Manage Display' tab, but not the 'Manage Fields' tab.

Does anyone know how to either get it to show up on that tab, or how to set the default text format on this field?

Alright, after lots of research I've come up with three different solutions to the issue.

Solution 1 (not so great):

On the text formats and editors configuration page (/admin/config/content/formats), the top format in the list that the user has permission to will be set as the text format automatically when saving the field (entity). If you only have a text format or two, this will work, but it is easily breakable, so it's not a great solution.

Pros - easy.

Cons - easy to break if/when someone adds a text format or re-orders them. Hard to configure. Not stable at all.

Solution 2:

In your form defintion for the entity (or a _form_alter hook for the form), you can set the format as follows. Note that in this case, my field is keyed as 'message:

public function buildForm(array $form, FormStateInterface $form_state) {
  $form = parent::buildForm($form, $form_state);

  foreach(\Drupal\Core\Render\Element::children($form['message']['widget']) as $element_index) {
    $form['message']['widget'][$element_index]['#format'] = TEXT_FORMAT;
  }

  return $form;
}

Note: Replace TEXT_FORMAT with the key of the text format you want to use.

Pros - can be overridden as part of the form by other developers

Cons - can be overridden as part of the form by other developers (if you want to ensure that the text format is always the same and cannot be changed)

Solution 3:

In your entity definition, first add this function (again, my field is keyed as 'message'):

public function setMessageFormat($format) {
  $this->get('message')->format = $format;

  return $this;
}

Then you can add a preSave() method to the entity definition to set the format:

public function preSave(EntityStorageInterface $storage_controller) {
  parent::preSave($storage_controller);

  $this->setMessageFormat(TEXT_FORMAT);
}

Note: Replace TEXT_FORMAT with the key of the text format you want to use.

Pros - Ensures your text format is always what you want it to be for that field on the entity

Cons - cannot be changed by anyone else if you want this to be configurable.


How to manage and delete orphaned node references? I have a product node type and a review node type. The review node type has a node reference field that points to product. I can make one product and many users can add through using the node reference URL widget several reviews. I've been deleting the products while the reviews have been sitting orphaned in the database. This hasn't been a problem till I installed the Search API module. Perhaps the error being caused by the Entity module is a bug but those pesky node references have no business existing if the product has been erased or at least they shouldn't be published.

I can think of many solutions to this including never letting a product be deleted so that all content stays in the database till the end of time.

However, I would like to just delete all the reviews when a product is deleted. How do I do this.

This situation is exactly like deleting comments which are entities when deleting the node they are attached to. So I looked at the code in comment.module to see how it is handled there. Here is my solution:

/**
 * Implements hook_node_delete().
 */
function helper_node_delete($node) {
  if ($node->type == 'product'){
    $nids = db_query('SELECT entity_id FROM {field_data_field_review_reference} WHERE field_review_reference_nid = :nid', array(':nid' => $node->nid))->fetchCol();
    node_delete_multiple($nids);
  }
}

This also means that I can test to see if the node type is a review so all node types that reference the review can be handled too since hook_node_delete is recursive in this instance.


View with pagination to have a single url per pagination page I was doing a View for a last news from a site, but those news won't be accesible from outside, so only will be able to see the content by the view.

This view has a Pagination, and is printed as page. The problem is that I need to implement the facebook comment plugin, and I need that every page listed by the pagination, to have a unique url, I thought that it could be the same as the node url.

I tried by doing something with panes, but I could't override the View page. I'm Using Drupal 7 and the lasted version of views.

Thanks

The url's are unique. If the page view has a url of /news, then each page can be referenced individually as /news?page=0 for the first page, /news?page=1 for the second page and so on.


How can I change the 'type' of Drupal script tags from text/javascript to text/plain? I could use some assistance in figuring out a way to change script tags for a Drupal 7 site to be "text/plain"  instead of "text/javascript" And additional attribute(s).  I can tell already that script injection is something that is all over the board when it comes to implementation. Facebook 'pixel' for example is injecting script code outside of the drupal_add_js mechanism. And there are plenty of script tags added in templates (which are simple to change as necessary) but I would like to come up with a solution for the actual Drupal injected scripts, and nothing I’ve tried has worked yet.

Reasoning

This change is required by the service provided via https://eucookie.eu/ for handling GDPR related functionality.  I technically only need to change scripts that are adding cookies.

What I've tried without success

Implementing hook_js_alter() in a module

This provides access to some script information, but I don't see a way to change the script type attribute at all.  I can however add attributes, just not alter the type as necessary.

Implementing phptemplate_preprocess_html_tag

mytheme_preprocess_html_tag(&$variables) {
  if ($variables['element']['#tag'] == 'script') {
    $variables['element']['#attributes']['type'] = 'text/plain';
    $variables['element']['#attributes']['data-cookie-if'] = 'analytical';
  }
}

The additional attribute of data-cookie-if IS being added as expected.  But the type is not being changed, in fact, there is no type at all in the resulting markup.

Additional complications

Script Aggregation if enabled will add another twist, and I'm fairly certain I will need to disable this, but still wanted to mention in case there is a preferred workaround.

I solved, mostly by implementing the theme_process_html_tag method in the template.  Note the PROCESS not PREprocess.

In my case, the theme was extending the 'zen' theme, which was actually removing all 'type' attributes from scripts in the header (I don't know exactly why).  But I was able to overwrite this behavior in the theme hook mentioned above.


Image re-sizing while uploading via drupal 7 dashboard I am looking for an option to re-size the images while uploading from a content type.

I can set the max upload size to 8 mb and while user uploads the images it should be resized to a lesser size automatically.

How can i do it?

Follow the steps.

1) Add new image style from Configuration->image style

2) Go to your content type and Edit the image field

3) Select your newly created image style from the "preview image style" dropdown list and then save settings.

Now the images will be resized according to your created style.


Why Drush cron go to view of nodes? i have a simple function to return 404 on some content-type

function module_type_node_view($node, $view_mode, $langcode) {
  // variables
  $type = $node['#node']->getType();
  $userRole = \Drupal::currentUser()->getRoles();
  // if is events2/subsidiary
  if(($type === 'events2' || $type === 'subsidiary') &&
  (in_array('anonymous', $userRole))) {
    throw new NotFoundHttpException();
  }
}

But if i run drush cron i have this error:

Symfony\Component\HttpKernel\Exception\NotFoundHttpException:  in module_type_node_view() (

The crohn is performed anonymously, I have no way to create an exception

I'm going to assume there is something running with cron like a search indexer or something handling nodes, and since it is run anonymously, it triggers this.


Image field upload shows a broken preview until I reload the page When I upload an image it does an AJAX upload and then tries to show the thumbnail but the thumbnail style of that image is not available, so it shows up as a missing image. If I save and come back to the form, then it displays fine.

make sure the "image style" of your image field exists. for example to make sure about our "Article" content type, we check the path below:

  http://yoursite.com/admin/structure/types/manage/article/fields/field_image

find your "image style" name and then go the path below:

  http://yoursite.com/admin/config/media/image-styles

check the image styles name and make sure "Article" image style is here. if it's not, you have to change image style of your content type.


Multiple account profiles I just started using profile2 module to implement 2 types of profile for my site visitors (sellers, buyers for example). Both type of users can post content (say articles). I know whenever someone posts an article, a relationship is created in the db between that user and article. What I want to do is to show a user's articles under that user's profile page (the page that the profile2 module creates). With drupal 6 and content profile, this was easily done with a few modules since profiles were nodes back then. I'm guessing I'll have to code up a module to do this since profile2 profiles aren't nodes anymore. Can you guys give me some pointers on how you'd/you've gone about accomplishing this? Much thanks!

Views is the way to go. Create a view with a block that lists articles, add a contextual filter to the user id and configure it to provide a default argument from the url. Then add that block to the user profile page, you should be set.


Autosave nodes, when editing or creating new ones, in database Looking for a way to actually save nodes every x seconds when creating or editing.

I am aware of the Autosave module, which is a great module but it only saves the forms on clientside and has quite it's issues and conflicts with several other modules on my website (jQuery Update, Drag 'n' Drop Upload,...)

So basically I'm looking for a way to save a node automatically in the drupal system, even when creating a new one. Some sort of "draft" function like Gmail uses for unfinished mails.

I think the best shot is to use an ajax script which runs every x seconds, but have no idea how to get it into the database...

Anyone who is aware of a similar module or could point me in the right direction how to achieve this?

I'm unaware of any existing production/beta modules with this functionality.
There's an old blog post available from 2014 that discusses the use of GarlicJS to save the current working version of the Drupal node you're working on in browser local storage:
https://www.shooflydesign.org/buzz/lightweight-autosave-for-drupal-with-garlicjs
Quote:

Garlic uses HTML5 local storage, supported by all browsers these days, to cache what you're writing as you write it. I like this solution because, unlike WordPress, it doesn't create a bajillion post revisions. The values are stored by your browser until your submit the form, at which point they're cleared out.

If you're open to updating to Drupal8 (likely not, I realize), then there's a new module available called AutoSave_Form that claims to do something similar to what you're asking for:
https://www.drupal.org/project/autosave_form
Quote:

The autosave form module comes with a configuration form, which could be found under Admin->Configuration->Content->Autosave Form. There the interval could be easily adjusted and decide whether autosave is turned on for content or config entity forms or for both. By default it is active only on content entity forms and currently it is being tested only with content entity forms. If support for config entity forms is required please feel free to open an issue if you find some bugs regarding config entity forms.
At the moment the autosave works only for entity forms, but it will be extended to cover regular forms as well.


How to create a User Feed using the modules Message and Flag? What I'm trying to do is in theory easy : **User** flagged **Article**. But I'm having hard time figuring out how to build a user feed like this with Message and Flag modules.

I looked a little bit at the Message UI to create a message type, but can't seem to find a "Flagging user" token. The only related flag token I've found is Users who flagged the entity with flag flag which prints all users that liked an article like this:

User A, User B, User C flagged Article

What I really need is to print a message for every flag, like this:

User A flagged Article
User B flagged Article

And finally show everything in a view to the Article author.

Any suggestions?

If you'd add the Rules module (on top of the Message and Flag module you're already using), you can get this to work by using the "Replacement tokens" as part of your "Message type" configuration.

If you're not familiar with these Replacement tokens, you can learn about it the answer to What's the purpose of "Replacement tokens" of a Message type? This answer also includes a sample rule which is similar to what you'll need: it makes the value of token flagging-user available to the Message type.

Some more details to resolve this specific question here:

Add a Replacement token in your Message type, and call it (say) @user_who_flagged (or %user_who_flagged if you prefer).
Use that @user_who_flagged (or %user_who_flagged) token anywhere you want in the message you're trying to produce.
Have Rules create your message (of the message type you're using), which you can do like so:

Rules Event "Article gets flagged".
Rules Action "Create an entity" (corresponding to your Message type, and use a variable like (say) entity_created for that).

Add an appropriate Rules Action to pass the value of the "Replacement token" (which is used in the Message type as detailed above):

which looks like entity-created:arguments:user-who-flagged, and
in which you pass the value flagging-user (that's the clue to make it work ...).

Should you want to include additional info in your message about the actual Article (like nid, content type, title, author, whatever), then just create an additional Replacement token for each of them, and a similar Rules Action for each of them also.

With the above approach you'll have your messages created with the custom content you want. Those messages are Drupal entities, so creating an appropriate view from it is straight forward.

For anybody not familiar with the (great) Message module yet (which is poorly dcumented ...), here is your chance to get a first impression about it ... Below is an export of "a" message type that you could use to get started (by simply importing it in your own site). It actually works together with the example rule in the related question. This message type has machine name user_following, and uses a replacement token like @following_user (adapt both to fit your needs, eg change @following_user to @user_who_flagged to use what I suggested above):

{
  "name" : "user_following",
  "description" : "User following",
  "argument_keys" : [ "@following_user" ],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "",
  "arguments" : null,
  "message_text" : { "und" : [
      {
        "value" : "@following_user started following [message:user:name]",
        "format" : "plain_text",
        "safe_value" : "\u003Cp\u003E@following_user started following [message:user:name]\u003C\/p\u003E\n"
      }
    ]
  },
  "rdf_mapping" : []
}

Notes:

(to avoid confusion) [message:user:name] in the message type sample above is the user to which the message is targeted, not the flagging user!
(if you still don't get the clue of all this) using Rules it's possible to make data originating from any module (such as the Flag module) available as tokens to the Message module.


Somebody is trying to brute force the password Looking at the site log, I found, that somebody with IP address: 91.236.74.135 is methodically sending requests to the page: /user?destination=node/add of my Drupal website. He does it once in every hour. It's definitely a bot. I think, he's trying to brute force the password. For now I banned him in .htaccess with

deny from 91.236.74.135

Can anybody give an advice, how to protect the site from brute force attacks on logins?

I have two ideas to help with this problem.

There are tools and services you can use to look for brute force attacks. The security review module and droptor tools both look in your watchdog (at Administer > Reports > Recent log messages) to see if you have a lot of failed logins for one user. You can also do that manually.

In Drupal 7 the "access rules" feature was removed from core but moved to a contributed module - User Restrictions. Using that module you can block users from a specific IP address. Apache deny rules will be slightly faster if you have relatively small number of rules but the Drupal rules are easier to add/update/remove.


Image field, how add title field? Here drupal have a field for set a description for each images:

How I can add a custom field for each image please ?
By example a "Title" or "Author" field ?
Thanks.

Have you tried "ImageField Extended"? Alternatively, you could create a new content type which consists of an image and any number of fields that you want.


Clean URL pagination (rewrite ?page=parameter) One of my client works with an SEO agency and they ask me to remove the pagination parameter ?page=x (generated by the Views module) and rewrite it like this:

Before:

/my-page?page=1

After:

/my-page-1

Is there a way to do it with Drupal? I don't see any option in the view or in Pathauto to do this.

Is it possible to handle this with a custom module or should I work with .htaccess file?

I've tried the Clean Pagination module but you have to manually set pages where clean pagination should work and the module doesn't seem to work properly.

You should write a PathProcessor that implements:

Drupal\Core\PathProcessor\InboundPathProcessorInterface
Drupal\Core\PathProcessor\OutboundPathProcessorInterface

Example:

file: modules/custom/mymodule/src/PathProcessor/MymodulePathProcessor.php

namespace Drupal\mymodule\PathProcessor;

use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Drupal\Core\Render\BubbleableMetadata;

class MymodulePathProcessor implements InboundPathProcessorInterface, OutboundPathProcessorInterface {

  public function processInbound($path, Request $request) {
    if (strpos($path, '/my-page-') !== 0) {
       return $path;
    }
    $page =  preg_replace("/^\/my-page-(\d+)/", '$1', $path);
      if (ctype_digit($page)) {
        \Drupal::request()->query->set('page', $page);
        return "/my-page";
    }
    else {
      \Drupal::request()->query->set('page', 0);
      return "/my-page";
    }
    return $path;
  }

  public function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    if ($path === '/my-page' && isset($options['query']['page'])) {
      $page = $options['query']['page'];
      unset($options['query']['page']);
      return '/my-page-' . $page;
    }
    return $path;
  }

}

file: modules/custom/mymodule/mymodule.services.yml

services:
  mymodule.path_processor:
    class: Drupal\mymodule\PathProcessor\MymodulePathProcessor
    tags:
    - { name: path_processor_outbound}
    - { name: path_processor_inbound}

We also need to do a custom alteration to the pager. For the full pager the links are not created as the usual link render elements, so they don't go through the processOutboud, instead the twig file (classy/templates/navigation/pager.html.twig) uses a custom format. The next hook function does the adjustment.

file: modules/custom/mymodule/mymodule.module

/**
 * Implements hook_preprocess_HOOK().
 * Implements hook_preprocess_pager().
 *
 * @param $variables
 */
function mymodule_preprocess_pager(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  if ($current_path === '/my-page')
  foreach ($variables['items']['pages'] as &$page_link) {
    $page =  preg_replace("/^\?page=(\d+)/", '$1', $page_link['href']);
    $page_link['href'] = 'my-page-' . $page;
  }
}


How to use subgroups in drupal_add_tabledrag() I am trying to implement a form that is themed with drupal table drag using subgroups. My form consists of a list of 'employees' that need to be assigned to different 'departments'. The order of the employees does not matter once they are inside a department.

The admin/structure/block table is similar to what I am looking for but with just the select box for region and no weights.

I've looked through the documentation here: http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_add_tabledrag/7 and I've also studied the admin/structure/block table code but after several hours of trying different combinations - I am stuck!

The block module uses custom JS and a template tpl file for outputting the table. I think this doesn't take full advantage of Drupal. Therefore, this solution should make use of theme_table and #ajax (for the region select fields).

If you want ajaxed example perhaps you can study the Display Suite UI.

In my opinion the easiest way to do this if you need similar functionality is just to use the block module tpl's and change the data presented inside it (from block region to your custom module regions)

to remove the weights, I think if you remove :

drupal_add_tabledrag('blocks', 'order', 'sibling', 'block-weight', 'block-weight-' . $region);

it will remove the ability to drag and sort the weight.

some rough examples for "Drupal compliant" way :

note: this is VERY rough code, you will need to adjust it heavily

function theme_example(&$variables) {
  // build the header
  $header = array(
    '', // this will be hidden when table drag run
    '', // this will be hidden when table drag run
    t('Block Region'),
    t('Region Area'),
  );
  // enabled region
  //$regions = region_area_grab_region('enabled');
  // substitute this to what ever your module provides
  // this should be in $form array
  $regions = array('example_one', 'example_two', 'example_three');

  $region = array('example_block_one', 'example_block_two', 'example_block_three');

  // Add table javascript.
  drupal_add_js('misc/tableheader.js');
  drupal_add_js(drupal_get_path('module', 'block') . '/block.js');

  // take notice of the key that will be related to real options
  // in the select box, this should be in $form array
  $options = array();
  foreach ($regions as $key => $region) {
    $options[$region] = $region;
  }

  // add additional class here
  $attributes = array(
    'class' => array('draggable'),
  );

  // building the table rows
  $rows = array();

  // looping for each regions
  foreach ($regions as $region) {

    // this is the heart of the draggable
    // take good notice for the region-manager (the table id), region-area-weight (group of rows class)
    // and regionarea-weight- $region (unique row class), you will need to add this to the form array
    // element NOT in the table row

    // if you want to emulate the block page table drag, comment out the drupal_add_tabledrag
    drupal_add_tabledrag('region-manager', 'order', 'group', 'regionarea-weight', 'regionarea-weight-' . $region , $hidden = FALSE);
    // build the region row

    // replace this with your form element array eg $variables['form']['whatever']
    $elements = regionarea_build_admin_region_form($region, $form, $form_state);

    $row = array();
    $row[] = '';
    $row[] = drupal_render($elements[$region['name']]['weight']); // replace this to actual form array for the weight
    $row[] = $elements[$region['name']]['name']['#value']; // replace this to actual form array for the value / title
    $row[] = drupal_render($elements[$region['name']]['enabled']); // optional
    $row = array_merge(array('data' => $row), $attributes); // merge the array, add draggable class
    $rows[] = $row; // build the row

    // ----------------------------------------------------------------------------------------------------------------- //
    // Usually up to this point is enough for just normal draggable, only continue if you have a sub child to drag
    // ----------------------------------------------------------------------------------------------------------------- //

    // build the block regions
    // now we looping for the sub child AKA regions as in the block region page
    foreach($region['regions'] as $regionkey => $blockregion) {
      // add two table drag, one for weight the other for 'region'
      drupal_add_tabledrag('region-manager', 'match', 'sibling', 'region-select', 'region-' . $blockregion, NULL, FALSE);
      drupal_add_tabledrag('region-manager', 'order', 'sibling', 'region-weight', 'weight-' . $blockregion);

      // replace this with your form element array eg $variables['form']['whatever']['children']
      $elements = regionarea_build_admin_blockregion_form($blockregion, $regionkey, $options, $form, $form_state);

      // build the current row
      $row = array();
      $row[] = '';
      $row[] = drupal_render($elements[$blockregion]['weight']);
      $row[] = $elements[$blockregion]['name']['#value'];
      $row[] = drupal_render($elements[$blockregion]['regions']);

      $row = array_merge(array('data' => $row), $attributes);
      $rows[] = $row;
    }

  }

  // some options to pass to the theme_table
  $element = array(
    '#empty' => t('There are no region area available'),
    '#attributes' => array(
      'id' => 'region-manager',
    )
  );

  // build the theme
  return theme('table', array('header' => $header, 'rows' => $rows, 'empty' => $element['#empty'], 'attributes' => $element['#attributes'])),
}


Paragraph how to get content level wise? Using module https://www.drupal.org/project/paragraphs.

On Admin side I have made content as a 3 level categories. Main Category, Sub Category, Sub Category.

Each category have their content as well.

On twig file when i print

{{ content }}

It display all data. Which is correct.

I need to fetch individual category & their content & do the styling for each.

How can i retrieve that each field in loop?

You can use this template file:

/themes/mytheme/templates/field--paragraph--field-category--faq.html.twig:

    <div{{ attributes }}>
        {% for item in items %}
            <div{{ item.attributes }}>{{ item.content }}</div>
        {% endfor %}
    </div>


Different views for taxonomy terms I am having vocabulary containing hierarchical taxonomy like this :

Category1

subcategory1

lastcategory1
lastcategory2

subcategory2

category2

I am using pathauto to taxonomies path .

Path are like this :
www.example.com/category1

www.example.com/category1/subcategory1

www.example.com/category1/subcategory1/lastcategory1

At first path i want to show all subcategories taxonomy of category1 .

At second path i want to show taxonomy detail page of subcategory1 and below details i want to show subcategories  of subcategory1 taxonomy .

At last path i want to show content connected to lastcategory1 taxonomy .

How can i accomplish this using views .

Note : I don't want to change the taxonomy paths . I am using drupal 7

See this tutorial. Looks like it does exactly what you ask.

The tutorial includes a video but here is the written explanation:

1) Create a Taxonomy Vocabulary here: admin/structure/taxonomy (And create a few terms)

2) Create a Taxonomy View here: admin/structure/views/add

You want to make sure that you choose "taxonomy" entities.

3) Add a contextual filter for "Taxonomy term: Parent term"

Make sure to select "Default Filter" and choose "Taxonomy term from url." Also, specify a "Default validation criteria" for "Taxonomy term" and choose "Convert taxonomy name to ID" and select "Transform dashes in url..."

4) Add a new page to this view, remove the contextual filter from this view and add a filter for "Taxonomy term: Parent term" and set it to "equal to" and leave the field there blank.

5) Save that view and create a new view here: admin/structure/views/add

Make sure this view is for a "Content" of type "Product Display" (or whatever entity bundle has the field for your taxonomy terms).

6) Add a contextual filter for your taxonomy term, mine was called "Product Categories"

Make sure this contextual filter displays "Contents of No Results." Also, specify a "Default validation criteria" for "Taxonomy term" and choose "Convert taxonomy name to ID" and select "Transform dashes in url..."

7) Add a "No results" item called a "View Area" and select "Page_1" from your first view (this is the second page we created)

8) Save this view and go back to the first view.

9) Add a "No results" item called a "View Area" and select the second view that we just made.

10) Make sure your title field in the Taxonomy View doesn't link to the taxonomy term, but it outputs the field as a link to "catalog/[name]" that way your catalog names are clickable


How can I output the absolute URL as link text for internal links on link fields? When using a link field without a link text and just with the URL, Drupal 8/9 outputs the relative path as the link text for internal links. How can I change that to either output the absolute URL or (even better) use the title from the entity in the link as the link text?
I am using the "Separate link text and URL" formatter provided by Drupal core.

Inspired by Link field title from entity/route, I created a preprocess function.
/**
 * Prepares variables for link fields.
 */
function mytheme_preprocess_field__node__field_links(&$variables) {
  /* If it's an internal link and there was no link title provided by the editor,
then use the entity label as the link text.*/
  $i = 0;
  foreach ($variables['element']['#items'] as &$item) {
    if($item->getUrl()->isRouted()) {
      $parameters = $item->getUrl()->getRouteParameters();
      if (!empty($parameters)) {
        foreach ($parameters as $entity_type => $id) {
          if ($entity = Drupal::entityTypeManager()
            ->getStorage($entity_type)
            ->load($id)) {
            $variables['items'][$i]['content']['#url_title'] = Link::fromTextAndUrl($entity->label(), $entity->toURL())
              ->toString();
            break;
          }
        }
      }
    }
    $i++;
  }
}


How can you make an HTML link? I need a link with another render array around it. More specifically I need a link around an image.

In the D7 days I'd just use a render array of type link and then set HTML to true and set the text as the image.

I was hoping to put it in a preprocess function.

The HTML attribute removal was documented in change record #2932803, but the example uses the now deprecated SafeMarkup::format function. The FormattableMarkup class allows a non-deprecated way to do this. The API page has some good examples such as below:

Remember that this is has security implications, and to only use FormattableMarkup when you absolutely need it with strict placeholders.

$value = FormattableMarkup::placeholderFormat('@variable', [':url' => $url, @variable => $variable]);

There's probably a better way to do this without printing the anchor element and href attribute yourself.


How to hide few default fields for specific user I want to hide fields such as password, email when a particular user tries to edit few fields of other users.

How can I achieve this?

Hi for this there is many possible way to achieve this you can use
https://www.drupal.org/project/field_permissions/releases/7.x-1.0-beta2
(The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.)
or by custom module

 function mymodule_form_alter(&$form, $form_state, $form_id) {

  if ($form_id === 'you_form_id') {

  if (in_array('user_role_type', $user->roles)){
    //do stuff

     // Use var_dump  to dump the $form array to see the fields.
     // var_dump ($form);

     unset($form['mail']);
     unset($form['pass']);
    }
  }
}


Simplenews + Mime Mail + SMTP = occasional blank email I have a client site that uses the Simplenews module with the Mime Mail and SMTP Authentication modules. The subscriber list has a little over 300 email addresses, and when newsletters go out the cron sends out batches of 100 messages per hour. Things usually go off without a hitch, but with the last newsletter one of the batches sent contained blank messages. I have been unable to reproduce the problem. Someone else reported the same problem here:

https://www.drupal.org/node/2378147

. . . but has of yet there has been no response, and I'm not convinced the problem lies with the Simplenews module itself. Has anyone else seen anything like this problem?

First step. Have you combed your logs in Drupal for errors?  And have your also looked at your web server PHP error logs?

With this random problem you are having I would expect to see something going on in the logs.

I have never used the Simplenews module or reviewed it's code so I cannot say how well the authors of the module addressed error handling the module.

Clearly you have a problem and it's been reported by other people. If you find no error in the logs then I would say that potentially the module does not have enough error handling written into it to diagnose the problem.

For what it's worth (purely for your own information), I will say that attempting to do an email newsletter from a a web server is not the preferred method. An email service provider should be used for that functionality if you have any concern for deliver-ability of your newsletter.


Language switcher does not display the correct link to the default language path I maintain a bilingual English/French website and the Language Switcher block is available on every page to allow the user to switch language. It works except on one particular taxonomy term page and all it's descendants:

When the language is set to English (default), the Language Switcher displays the correct links. English links to the EN page and French links to the FR page.

But when the language is set to French (i.e the user has clicked on French), both English and French options link to the french page (with /fr/rest-of-the-path/).

Any idea where the cause of this behaviour lies in?

I think this happens because the term itself have no multilanguage path. From my experience the only way to have mulitlanguage path to a term is to create them by hand with an URL-Alias or by installing the [Pathauto i18n Taxonomy][1] Module. This helped me a lot


Abstract Base Class versus Service with Queue API I'm trying to figure out the best way to structure a custom module that uses the Queue API in D8.  I'm new to D8 and a bit rusty with OOP so forgive me if I'm breaking some recommended design pattern here...

I created a single custom module where multiple different queues need to process items differently, but each queue has common functionality that they may need to use between each other.  So my question is, should I create an abstract base class that extends QueueWorkerBase, make processItem abstract, and then add common functionality to the base class?

Something like this:

In src/Plugin/QueueWorker/ProcessQueueBase.php

abstract class ProcessQueueBase extends QueueWorkerBase {

  /**
   * @inheritDoc
   */
  abstract public function processItem($data);

  protected function doSomethingCommon(){
    // Some common logic
  }
}

In src/Plugin/QueueWorker/ProcessQueueOne.php

class ProcessQueueOne extends ProcessQueueBase {

  /**
   * @inheritDoc
   */
  public function processItem($data){
    // Do stuff now

    parent::doSomethingCommon();
  }
}

In src/Plugin/QueueWorker/ProcessQueueTwo.php

class ProcessQueueTwo extends ProcessQueueBase {

  /**
   * @inheritDoc
   */
  public function processItem($data){
    // Do stuff now

    parent::doSomethingCommon();
  }
}

OR should I create separate classes that all extend QueueWorkerBase and then just create services for the common functionality.

Something like this:

In DoSomethingService.php:

class DoSomethingService {

  public function doSomethingCommon(){
    // Do something
  }

}

In src/Plugin/QueueWorker/ProcessQueueOne.php

class ProcessQueueOne extends QueueWorkerBase {

  /**
   * @inheritDoc
   */
  public function processItem($data){
    // Do stuff

    $do_something = \Drupal::service('mymodule.doSomething');
    $do_something->doSomethingCommon();
  }
}

In src/Plugin/QueueWorker/ProcessQueueTwo.php

class ProcessQueueTwo extends QueueWorkerBase {

  /**
   * @inheritDoc
   */
  public function processItem($data){
    // Do stuff

    $do_something = \Drupal::service('mymodule.doSomething');
    $do_something ->doSomethingCommon();
  }
}

I would suggest an abstract base class, but instead of creating another function ::doSomethingCommon, partially implement ProcessQueueBase::processItem and call parent::processItem from the subclasses.


Form, populate select lists values after unsuccessfull validation I would like to have select values in my select lists that user poster to script. However when validation is not valid, those fields aren't populated with posted data, so user have to make the choice again. Could somebody give me any advice?

Code:

   for($i = 0; $i < 3; $i++) {
            $form['register']['cocktails']['cocktail']['bartender_cocktail['.$i.'][]'] = array(
                '#type' => 'select',
                '#default_value' => variable_get('bartender_cocktail['.$i.'][]', NULL),
                '#options' => $cocktails,
            );
        }

Your use of [] in the select name most likely confused the form API.

Try something like this instead:

for($i = 0; $i < 3; $i++) {
  $form['register']['cocktails']['cocktail']['bartender_cocktail'][$i] = array(
    '#type' => 'select',
    '#default_value' => variable_get('bartender_cocktail_' . $i, NULL),
    '#options' => $cocktails,
  );
}

Then, you need to set #tree to TRUE, so that you your cocktails into an array.

$form['register']['cocktails']['cocktail']['bartender_cocktail']['#tree'] = TRUE;

Then, you should be able to access the vaules like this: $form_state['values']['bartender_cocktail'].


get file path of image style as replacement patterns in views i need something like

<img attribute1='value' src='sites/default/files/styles/thumbnails/**pic_0**.jpg'>

in views.

i have to use rewrite result because i need attribute1. but i have no idea how to get src of image.
[filename] is not always same with file path. -for example [filename] is pic.jpg but file path is pic_0.jpg- .

and [uri] give me http://example.com/sites/default/files/pic_0.jpg  not http://example.com/sites/default/files/styles/thumbnails/pic_0.jpg.

how can i get pic_0.jpg or http://example.com/sites/default/files/styles/thumbnails/pic_0.jpg?

You can get file path of image style in view.tpl

Example:

/**
 * field with image: "field_image"
 * uri:  (image from field_image) File: Path
 */

$style_name = $view->field['field_image']->options['settings']['image_style'];
$thumb_path = image_style_url($style_name, $uri);

I didn't wrote how to get $uri because it depends on type of template file. The general idea is to get a file path of image style by using image_style_url($style_name, $uri) in view.tpl file.


Openlayers map with dynamic markup I have an open layers view that displays the numbers of reports for each country.

Can i display it other way for instance with dynamic circles markups :
3 reports : small circles , 50 reports : medium circles etc ...

example:
http://reliefweb.int/

You can do that by passing a context function in Javascript that replaces the $-placeholders in your style object. I gave an example in this answer. The linked answer only changes the icon based on term rather than changing the marker size, but the principle's the same. Let me know if I can be of more help.

Edit: Sorry, I hadn't looked at your example when answering. That map doesn't involve clustering, so I think you can do it purely via the GUI. First you need to get the number as a field in Views and then use the appropriate placeholder (which you can see when you preview the data overlay display of the view) in the pointRadius field of the map's style.

Details

Make sure that the report count is a field in the OpenLayers Data Overlay display of your view.
Look at the preview of this display and note down the placeholder for the field - something like ${field_report_count}.
Go to Structure -> OpenLayers -> Maps and edit the appropriate map.
Go to Layers & Styles, scroll down to OVERLAY LAYERS and look for the line which starts with the name of your view (it should end with - OpenLayers Data Overlay). Note down the name of the style in the STYLE column.
Go to Structure -> OpenLayers -> Styles and edit the style you noted down from step 4.
Put the field name you noted down from step 2. in the fields pointRadius and label. (I've never used the label field but I assume it does what you want.) You can also change the labelAllign, labelXOffset and labelYOffset fields if you want.


Add a new column to the backend I am trying to add a new column to a table and I added the column using hook_update_N().
function cca_update_8902(&$sandbox) {
  db_add_field('cca_findings', 'cca_topic_id', array(
    'type' => 'float',
      'not null' => FALSE,
      'description' => 'interim fields addition',
    ));
  \Drupal::entityDefinitionUpdateManager()->applyUpdates();
}

My field is also defined in the cca_findings class as property.
class cca_findings extends ContentEntityBase {

  use EntityChangedTrait;

  /**
  * {@inheritdoc}
  */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['cca_topic_name'] = BaseFieldDefinition::create('string_long')
      ->setSettings(['max_length' => 2047]);
    $fields['meanvalue'] = BaseFieldDefinition::create('float')
      ->setLabel(t('meanvalue'));

    $fields['cca_topic_id'] = BaseFieldDefinition::create('float')
      ->setLabel(t('cca_topic_id'));

    return $fields;
  }

}

So, the column has been created correctly, but the values are not going on the backend. I feel I am missing something.
What is missing in the code I wrote?

As described in Support for automatic entity updates has been removed, when a module needs to update its own entity, and the update must change the database schema, the module needs to implement hook_post_update_NAME(). That is what the Taxonomy module does in taxonomy_post_update_make_taxonomy_term_revisionable() to make its entity revisionable.
The key code lines in that hook, which show how a new entity field is added, are the following ones.
$definition_update_manager = \Drupal::entityDefinitionUpdateManager();
$last_installed_schema_repository = \Drupal::service('entity.last_installed_schema.repository');
$entity_type = $definition_update_manager->getEntityType('taxonomy_term');
$field_storage_definitions = $last_installed_schema_repository->getLastInstalledFieldStorageDefinitions('taxonomy_term');
$field_storage_definitions['revision_id'] = BaseFieldDefinition::create('integer')
  ->setName('revision_id')
  ->setTargetEntityTypeId('taxonomy_term')
  ->setTargetBundle(NULL)
  ->setLabel(new TranslatableMarkup('Revision ID'))
  ->setReadOnly(TRUE)
  ->setSetting('unsigned', TRUE);
$field_storage_definitions['revision_default'] = BaseFieldDefinition::create('boolean')
  ->setName('revision_default')
  ->setTargetEntityTypeId('taxonomy_term')
  ->setTargetBundle(NULL)
  ->setLabel(new TranslatableMarkup('Default revision'))
  ->setDescription(new TranslatableMarkup('A flag indicating whether this was a default revision when it was saved.'))
  ->setStorageRequired(TRUE)
  ->setInternal(TRUE)
  ->setTranslatable(FALSE)
  ->setRevisionable(TRUE);
$definition_update_manager->updateFieldableEntityType($entity_type, $field_storage_definitions, $sandbox);

In your case, the code for hook_post_update_NAME() would be similar to the following one.
$definition_update_manager = \Drupal::entityDefinitionUpdateManager();
$last_installed_schema_repository = \Drupal::service('entity.last_installed_schema.repository');
$entity_type = $definition_update_manager->getEntityType('entity_machine_name');
$field_storage_definitions = $last_installed_schema_repository->getLastInstalledFieldStorageDefinitions('entity_machine_name');
$field_storage_definitions['meanvalue'] = BaseFieldDefinition::create('float')
  ->setLabel(t('meanvalue'));
$field_storage_definitions['cca_topic_id'] = BaseFieldDefinition::create('float')
  ->setLabel(t('cca_topic_id'));
$definition_update_manager->updateFieldableEntityType($entity_type, $field_storage_definitions, $sandbox);

Replace 'entity_machine_name' with the machine name of the entity.


comment form custom validation I am using a custom validation in my Drupal 7 comment form.I want to match the comment_body against a word "example" so if someone just type "example"in the comment body then it will show a error message that only the word "example" is not allowed. After reading drupal api documentation i codded like this:

function mango_form_comment_node_news_form_alter(&$form, &$form_state, $form_id){
    $form['comment_body']['#prefix'] = '
Post your comment now!
';
    $form['actions']['submit']['#value'] = 'Post Your Comment';
    $form['#validate'][] = 'banana';
}

function banana($form, &$form_state) {
  if ($form_state['comment_body'] == "example") {
    form_set_error('comment_body', 'Your comment can not contain example!');
  }
}

Do not working :'( what i'm missing? Thanks

The values for comment_body is not stored in $form_state but in something like:

$form_state['values']['comment_body']['und'][0]['value']

function banana($form, &$form_state) {
  if ($form_state['values']['comment_body']['und'][0]['value'] == "example") {
    form_set_error('comment_body', 'Your comment can not contain example!');
  }
}


How do I get the video media path in a theme? I want to embed a video on a page.
How do I display the field_media_video_embed_field in my twig?
The complicated thing about this is that I am using a view inside tabs.
{{ kint(programme.video) }} gives me the following output.

In my theme I have used the following code.
$programmes = [];
$view = Views::getView('participating_programmes');
$view->execute();
foreach ($view->result as $row) {
  $video = $row->_entity->get('field_pvideo')->referencedEntities();
  $programmes[$nid]['video'] = $video;
}

Ideally I want to embed the video, but I would be happy if I could just get the field_media_video_embed_field and work from there.

It's unclear whether you want to get one or multiple videos:
// get one video media entity
$video = $row->_entity->get('field_pvideo')->entity;
// get multiple video media entities
$videos = $row->_entity->get('field_pvideo')->referencedEntities();

Then in Twig for one video:
{{ programme.video.field_media_video_embed_field.value }}

or multiple videos:
{% for video in programme.videos %}
  {{ video.field_media_video_embed_field.value }}
{% endfor %}


How to install drush on a restricted shell access account? Media Temple shared environment I'm working with a client that has a media temple server (gs)-gridserver. its a shared environment, but i do have access to the shell.

How would i go about installing drush for an account like this?

Place drush into your home (~) folder under something like ~/drush/
Create or edit ~/.bash_profile and add the following: alias drush='~/drush/drush'; this creates an alias called 'drush' that will execute drush's main file.
If you need to specify which version of PHP to use, add export DRUSH_PHP=/path/to/php.
Run source ~/.bash_profile to reload the .bash_profile file.

At this point you should be able to use the drush command.

In unrelated news: if you can, move your client off MediaTemple. Their database servers are in a physically different location from their web servers, which is an absolute nightmare for applications with a ton of database queries (read: Drupal).


What it's the easiest way to add a flash frontpage without alter Views node page? I'm using Views to render content in frontpage, but now, I want create a single flash presentation page as frontpage that links to the current frontpage.

Try using Themekey if its a different look and feel altogether... or Frontpage. Although you can create a node and have that node set as the frontpage in the sites configuration page. You have to use jQuery to have the page render the flash in drupal. As for redirection, what you will have to do is create a jQuery or actionscript that gets redirected at the end of the presentation or use the rule module that gets the page redirected after your particular condition is met. That is what I used on a previous project.


Combine integer fields filter My need is to combine fields which their data type is integer.

I did not find a module for that. Or is there? The "Global: Combined fields" filter supports strings only.

Which approach would you recommend to achieve this? Thanks!

[Edit]

After seeing a comment from @scronide I am adding here some info (this is more generic so I do not comment his comment).

One might indeed choose the direction of saving a value in another field. It may be indeed as a computed field, but also as another integer field which - in its turn - holds the wanted value using code or rules.

However, I wanted to consider the on-the-fly retrieving the items.

Still, may be the separate field direction is better to go with. I will give here my exact situation, also as @Roy Segall suggested.

GIVEN
 - Using Search API indexes for the view's exposed filter;
 - Multiple integer field in a few content types. In the "Person" content type I have: "Year born", "Was active from", "Was a king from", etc. In another content type "Work" I have "Year written", "Year published", etc.

NEED
- The exposed filter is in a view where both content types are located and should return results of any item of any content type which holds a value bigger than or equal to the search value in any of the integer fields.

NOTE
As I am not an expert regarding performance, I am not sure which direction is the way to go; that is, saving a separated field (shared one across types) and index it for a simple filtering, or rather indeed filter on the fly among multiple fields.

Thanks for using your calories in your brain to help me think...
Amir

Add a Computed Field to the content type to calculate the sum of the other fields–stored as an integer–and then you can use it as a Views filter. You will need to re-save your nodes to generate the computed field values.


Path alias as arguments in views I would like to pass path alias as arguments to a views page. I tried the two methods one and two but unfortunately this doesn't works.

What I want to do is, example.com/box/portfolio link should show the example.com/box/45, 45 is node of portfolio. My views page path is box/% and I used the arguments as Node Id.

Looking into the Views Alias module, it does exactly what you need. Rather than making the change during the Views argument validation, this module will create a path alias to this View for every taxonomy term that can be an argument on the Views you select. Thus, example.com/box/45 can be accessed via example.com/box/portfolio, etc.


Migrate existing dev desktop site from PC to Mac without existing db dump I have a PC with dev desktop on it where I had a local install of a drupal 7 site.
I needed to reinstall windows on the PC and it wiped out my local install except I kept the old windows files, so I have access to the original site files.

What I don't have is a database dump of the local install.

With the old files, is there a way I can find the database table data?  I can see in the old install of dev desktop the mysql/data content for the site, but I think I need additional files to complete the database tables, etc.

Thanks.

DevDesktop stores the mysql databases in its application installation folder.  Assuming, you installed to the default location, in your PC backups, navigate to C:\Program Files (x86)\DevDesktop\mysql\data
This folder contains a copy of the MySQL databases.

Restoring to PC for use or export:

On the PC (assuming you haven't installed any other devdesktop sites), copy all the files and folders from the mysql/data backup directory into a fresh install's MySQL's data directory.
For export:  Start MySQL and export a copy for backup purposes/importing elsewhere as needed.
For immediate use/development on PC: Start MySQL and your DevDesktop to confirm the site is running; resume normal dev desktop development on PC

Loading directly to a fresh install of DevDesktop, MAMP, Vagrant, or other MySQL service on Mac

You could also copy the contents of that backup folder directly to the corresponding mysql/data backup directory on your Mac.  NOTE: copying the entire directory will wipe all existing databases/user accounts in MySQL on your Mac's MySQL server, be sure to back it up first if you have existing data).  If it's a fresh install of DevDesktop (or other) on the Mac, copy all the files and folders from the mysql/data backup directory of the PC to the corresponding folder on the Mac.
Start DevDesktop or other local webserver app to confirm the site is running; resume normal dev desktop development on Mac

Merging with existing mySQL data, hosting database along side others on existing install of DevDesktop, MAMP, Vagrant, or other mySQL service on Mac

If you do have existing MySQL data on the Mac (be it MAMP, DevDesktop, Vagrant instance or other), backup the corresponding /mysql/data folder from that application.
Replace with the backup folder from the PC
Start MySQL and export the database.
Then swap the original Mac MySQL data back into place.
Restart MySQL and import the database backup you just exported.
Now you have both your PC devDesktop database and Mac databases available on the Mac.


How can I attach an existing server image to an image field rather than uploading a new image file? Is there a module or some other way of attaching an image to an image field by selecting the image from existing files on the server rather than upload a new image?

I'm working on a project where many nodes have an image field. That image is displayed in various places at different sizes using image styles.

The users are migrating from another system and they're very used to the "image library" concept. They like to upload images that they will later use in various places around the site. The standard image field on a node only lets you upload from the local file system.

Ideally we'd like to have a "browse server" button instead of the upload button but end up with the same resulting image field.

The Media module comes tantalizingly close and I'm sure we'll use it for videos etc but it creates a media asset field, not an image field which I don't think can be resized with image styles and used so easily in views etc.

I tried the image picker module late last night. Maybe I need to try it again but I don't think I quite understood it. We don't really want resizing and create thumbnails etc on the node edit screen. We really just want a way to create an image field where the path points to an existing file somewhere below /sites/default/files. The files will be uploaded with something like IMCE.

Thanks for any ideas.

I think Filefield Sources along with IMCE does what you need.


how to get the values from views in page template I created a view (page name 'Archives') to load the following values from all the posts of a particular content type.
Year = field_year
Volume = field_volume
Issue = field_issue
By using views I couldn't get the desired output. So, I created a template file (views-view--archives--page.tpl.php) and wrote the following code. Please see the attached screenshot & code below. Please help me in correcting the code. This would be a great help. Thanks

 <?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>

    <?php print $item['field_year']." (volume - ".$item['field_volume'].")"; ?>
    <?php print "Issue ".$item['field_issue']; ?>

 <?php endforeach; ?>

You should use the Views templates (under Advanced > Other > Theme: Information). It gives several output types. When you create a Views specific template file, it passes a whole bunch of variable/values that you have chosen in your Views to the Views template file. Then you are free to use it like how you want. Read more info at http://views-help.doc.logrus.com/help/views/analyze-theme


Hide summary if empty (no trimming) In many cases we're using a view of content using the summary or trimmed text of a body field. Clients sometimes remark that, if there's nothing in the summary, nothing should be displayed at all, so no trimmed text of the full content either (which Views does by default).

Instinctively I went looking in the Behaviour when no results options of that body field in the View, but couldn't find anything there that would hide the summary if the summary is empty, disregarding what's in the full content.

What would be the recommended approach to achieve this?

Check the Rewrite the value of this field-option of the body field,
Fill out the following token in the text area: [body-summary]

Now it will only display text from the summary, and nothing when that very summary is empty. So it won't use the trimmed text of the full content either. Perfect.


Execute user_save() after the form submission handler In my implementation of hook_form_alter() I am using the following code; it executes mymodule_user_form_submit() before user_save().

array_unshift($form['#submit'], 'mymodule_user_form_submit');

user_save() is not executing after that.

What is the problem with this code?

I want to execute user_save() after mymodule_user_form_submit().

function mymodule_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'user_register_form') {
    drupal_set_message("Form ID is : " . $form_id);
    //$form['#submit'][] = 'custom_user_form_submit';
    array_unshift($form['#submit'], 'mymodule_user_register_submit');
  }

}

function mymodule_user_register_submit(&$form, &$form_state) {
//code goes here
$form_state['field_magentopass']['und'][0]['value'] = $form_state['values']['pass'];
}

if the code is wrong how can i assign the value to this variable $form_state['field_magentopass']['und'][0]['value']

or this entire method is wrong?
should i go for any other alternatives?

In your code, your submit handler ( mymodule_user_register_submit ) and actual function name ( custom_user_form_submit ) are different.

Also, your submit handler is using

$form_state['field_magentopass']

instead of

$form_state['values']['field_magentopass']...

It should be something like

/**
 * Implements hook_form_FORM_ID_alter
 * User register form id: user_register_form
 */
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  drupal_set_message("Form ID is : " . $form_id);
  array_unshift($form['#submit'], 'mymodule_user_register_submit');

}

function mymodule_user_register_submit(&$form, &$form_state) {
  $form_state['values']['field_magentopass'][LANGUAGE_NONE][0]['value'] = $form_state['values']['pass'];
}

UPDATE: OP changed their question to use matching function names. Apparently new $user is saved, but field_magentopass wasn't updated.

Lastly, an alternative approach, based on form_set_value and the #validate handler

/**
 * Implements hook_form_FORM_ID_alter
 * User register form id: user_register_form
 */
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  drupal_set_message("Form ID is : " . $form_id);
  $form['#validate'][] = 'mymodule_user_register_validate';

}

function mymodule_user_register_validate($form, &$form_state){
  $form['field_magentopass']['#parents'] = array('field_magentopass');
  form_set_value($form['field_magentopass'], array(LANGUAGE_NONE => array(0 => array('value' => $form_state['values']['pass']))), $form_state);
}


Grouping data to be displayed in the a template. I have the following related Content types:

I am creating a view to get the following output

Resource Title
Resource Type. (If type is Quiz, then also show the following data)

Quiz Title

Option Title 1
Option Title 2

Currently, i am getting the following output

Resource Title
Resource Type
Quiz Title
Option Title 1
Resource Title
Resource Type
Quiz Title
Option Title 2

How can I group the data in the templates to get the desired result?

Thanks

An approach I have used at the moment is to use a preprocess hook in my template. Added the following preprocess template to a custom module

THEMENAME_preprocess_views_view_unformatted__PAGENAME(&$variables)

where variable is an array containing
- view : the view object
- rows : an array of row items and each row is an array of content.

I looped over the data and constructed my required object, which then I set as a new property resource  (i.e. $variables['resource']) of variables.

Within the template (views-view-unformatted--PAGENAME.html.twig), I then have access to the resource variable to use in the twig template. e.g {{ resource.type }} , where type is a property added to the resource variable in the preprocess hook.

Not sure if this is the best way to approach the problem, but at least it is one way of approaching the problem.


Create menu for contextual view page I have a series of pages created through Views, all the view pages are relative to one piece of content. The content paths I have created are

 - mycontent/[nid]/overview
 - mycontent/[nid]/members
 - mycontent/[nid]/content

Not that whats inside the view is particularly important but in this example, the first one shows the basic information about the node, the second shows everyone who is referenced by an entity reference, and the third shows all nodes connected by an entity reference.

I have created a new menu called 'mycontent-submenu' which I want to fill with links of:

 - Overview
 - Members
 - Content

Obviously you cannot use the Views module's menu ability to provide this as a menu item (unless you want to use it as a tab, which unfortunately I don't). In a more general term, the first question would be, how can I put these pages into a proper Menu (ie, not a tab)?

I already know of 1 way in which to solve this, which is to use Menu Views, with that I made a view for each of the Overview, Members and Content page, set the limit to 1, applied a 'null' contextual filter, and forced the output of the view to be re-written as 'mycontent/!1/overview'. Which works, but its a little hacky for my liking, plus you're querying the database a lot, I've done it before and it ended up increase the page load time if you have multiple menu items.

What I want to try to do right now is try to make a menu item programmatically in my own custom module, but I don't know what I'm doing wrong. My current code is:

function mymodule_menu() {
  $items['mycontent/%nid/overview'] = array(
    'title' => 'Overview',
    'description' => 'View the item',
    'menu_name' => 'menu-mycontent-submenu',
    'page callback' => views_page('individual_item', 'item_overview'),
    'page arguments' => array(1),
    'access callback' => TRUE,
    'expanded' => TRUE,
  );

  $items['mycontent/%nid/members'] = array(
    'title' => 'Members',
    'description' => 'Item members',
    'menu_name' => 'menu-mycontent-submenu',
    'page callback' => views_page('individual_item', 'item_members'),
    'page arguments' => array(1),
    'access callback' => TRUE,
    'expanded' => TRUE,
  );

  $items['mycontent/%nid/content'] = array(
    'title' => 'Content',
    'description' => 'All the Content for this item',
    'menu_name' => 'menu-mycontent-submenu',
    'page callback' => views_page('individual_item', 'item_content'),
    'page arguments' => array(1),
    'access callback' => TRUE,
    'expanded' => TRUE,
  );
}

As far as I can tell, I've researched how you call a view within a page callback, which is views_page, and I've declared that I want my links to go into the right menu structure, but nothing actually appears. Is this block of code correct for what I want to do.


Aegir login link not working I am trying to install Aegir on Ubuntu.

I followed the installation instructions

sudo mysql_secure_installation
echo "deb http://debian.aegirproject.org stable main" | sudo tee -a /etc/apt/sources.list.d/aegir-stable.list
curl http://debian.aegirproject.org/key.asc | sudo apt-key add -
sudo apt-get update
sudo apt-get install aegir3

Everything got a success, but when I go to the login link that it provides me, the I get "server DNS address could not be found."

When I go to mydomain.com I get a 404 (which was working before).

Why is this happening? What am I missing?

I hate providing a link answer, but in http://docs.aegirproject.org/en/3.x/install/#debianubuntu do steps 1-6 then you can install Aegir.

They main key being you need to do sudo hostname yoursite.com which was not mentioned in other docs.


Submit form and redirect to same form I have contact webforms in all pages on footer including the front page template. I want the user to be redirected to the same page they are in and but the message that the form have been submitted should be visible.

How can i do that? Is there a built in method.

A solution that comes in mind is:

Install Rules and Webform Rules
Go to your webform and at form settings set Redirection location: No redirect (reload current page)
Add a rule, when a webform is submitted to fire action "Show a message on the site".


How do I implement the equivalent of hook_url_inbound_alter()? I'm working on a module which will resolve URLs to entities by altering inbound URLs so that if they contain an entity ID with following pattern "-{entity_id}" user will be redirected to correct URL.

A working example of the above:

Final URL:

http://romajazz.it/concerti/pozzovio-de-angelis-4902
Using the aliases:
http://romajazz.it/concerti/-4902
http://romajazz.it/concerti/i-can-type-anything-here-4902

I researched for a while; I found out there was hook_url_inbound_alter() in Drupal 7 which could solve this problem.

I also found that there is InboundPathProcessorInterface in Drupal 8.

I thought about implementing InboundPathProcessorInterface and use it in EventSubscriberInterface implementation which will subscribe on KernelEvents::REQUEST.

I wonder if this approach is correct. Are there any other ways of doing this in Drupal 8?

The PathProcessorAlias() class is probably your best example.

Create a module with a class the implements InboundPathProcessorInterface.
Create the service definition in your module.
Make sure your service has the path_processor_inbound service tag.  This will mark it for collection and tie it to the path processor.  You may need to play with the priority to change where it runs.

Your class will need to have some injected dependencies for looking up the entity.  EntityManager() got broken up recently, and I forget which ones you will really need.  You may also need/want the PathValidator() service.


Table 'watchdog' was not locked with LOCK TABLES on custom module I am creating module that need to lock table:

db_query('LOCK TABLES {eventi_list} READ');

$is_booked = _is_booked($uid, $nid);
if (! $is_booked) {
  $is_booked = _is_booked($uid, $nid, 'eventi_waiting_list');
}

if (! $is_booked) {
  $amount = _get_free_amount($nid);
  if ($amount > 0) {
    $insert = db_query("INSERT INTO {eventi_list} (uid, nid) VALUES($uid, $nid)");
  }
  else {
    $time = time();
    $insert = db_query("INSERT INTO {eventi_waiting_list} (uid, nid, created_at) VALUES($uid, $nid, $time)");
  }
  $update = db_query("UPDATE {content_type_event} SET field_event_places_amount_value = field_event_places_amount_value - 1 WHERE nid=$nid");
}
db_query('UNLOCK TABLES');

I am getting error (4 similar warnings):

Warning: Table 'watchdog' was not locked with LOCK TABLES query:
INSERT INTO watchdog (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (19, 'php', '%message in %file on line %line.', 'a:4:{s:6:"%error";s:12:"user warning";s:8:"%message";s:139:"Table eventi_waits was not locked with LOCK TABLES query: SELECT count(nid) AS count FROM eventi_waits WHERE nid=201 AND uid=19";s:5:"%file";s:95:"D:\tools\xampp\htdocs\drupal\sites\bartenders.localhost.com\modules\\custom\eventi\eventi.module";s:5:"%line";i:115;}', 3, '', 'http://bartenders.localhost.com/bartender/book/201/%3Fdestination%3D/eventi/justin-knows', 'http://bartenders.localhost.com/eventi/justin-knows', '127.0.0.1', 1303900341) in D:\tools\xampp\htdocs\drupal\includes\database.mysqli.inc on line 135

What can I do with this, turn off database reporting?

This won't work with the current code. It is not the reporting that is the problem, but the implementation of locking.

From mysql lock tables reference

  A session that requires locks must
  acquire all the locks that it needs in
  a single LOCK TABLES statement. While
  the locks thus obtained are held, the
  session can access only the locked
  tables.

You are trying to access unlocked tables while holding a lock.

I can't say that I have used it in the wild but there is a Drupal specific  locking mechanism that you may want to look at instead.


Save order data in a plain text file Just like the order data can be sent via email, I want to save the order data in a plain text file in a specific directory on the same server as the drupal installation.

Is it possible? How can I achieve this?

Saving a file should be a fairly simple job with PHP. If you want to do it when an order is completed, you could make a conditional action for it, or use one of the hooks that's invoked when the order is completed.

If you have an concrete problems on how to do this, you should refine your question.

If you want to save the mail sent, this would hold the order info, you could create a custom module and use hook_mail_alter to get the mail text:

/**
 * Implements hook_mail_alter().
 */
function my_module_mail_alter(&$message) {
  if ($message['id'] == 'uc_order_action-mail') {
    $message_text = $message['body'];
    // Code to save text as txt file here.
  }
}

By default the mail sent with ubercart is a HTML mail, so you might want to create your own text instead.

Whatever you do, you shouldn't alter Drupal or any of the modules, you should create your own module(s) that make the alteration. If you are new to Drupal development, you should read the developer guide.


How do I send an email to all users that has flagged a node using rules? I need to send an email when there is a new comment on a node to all users that have flagged that node? How do I do this?

The flag is called "Follow" and the content type is "Blog"

The exported code assumes use of Flag module to have a flag type as "follow" attached to Blog content type.

As a summary:

set rule event as "After saving a new comment of type Blog comment".
leave condition as none.
set actions as

step 1: get all users
who have flagged "Fetch users who have flagged a Node".
step2: loop
through the list.

step2.1: send email

Here is the export for my Rule configured as per your requirement.

{ "rules_email_on_blog_comment" : {
    "LABEL" : "Email On Blog Comment",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "blog", "email" ],
    "REQUIRES" : [ "flag", "rules", "comment" ],
    "ON" : { "comment_insert--comment_node_blog" : { "bundle" : "comment_node_blog" } },
    "DO" : [
      { "flag_fetch_users_node" : {
          "USING" : { "flag" : "follow", "node" : [ "comment:node" ] },
          "PROVIDE" : { "users" : { "users" : "Users who flagged" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "users" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "mail" : {
                "to" : "[list-item:mail]",
                "subject" : "New Comment",
                "message" : "There is a new comment on the flagged blog post",
                "from" : "[site:mail]",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}


email address not appearing in user profile I am using drupal 7 default user_register module, when a user registers with all the required fields, it successfully registers but when I click that user in people> tab his/her profile is displayed in which email is not appearing as you can see in the screen shot. Whereas when I clicked on edit link on the right side of that user email address exists.

copy the default profile template into your theme directory (the default template I copied is /modules/user/user-profile.tpl.php)
just after the initial  insert this code:

$profile_user = user_load(array('uid' => arg(1)));

 if($profile_user) {

   print '
Contact Information
';
   print '

Email
';
   print '
mail . '">' . $profile_user->mail . '

';
 }

That's it, all your profiles should have email addresses.


Override a view definition programmatically I want to override a view definition programmatically (using the code that I get from "view export" in the views admin pages).

I've found examples for creating views using views_new_view(), but nothing on modifying views definition programmatically. Are there any examples / tutorials on this ?

Can I do this with views_get_view($name) / views_save_view() ?

Ok, I got to a working solution :

$my_view_name = 'my_test_view';

$view = views_get_view($my_view_name);
if ( $view ) {
  views_delete_view($view);
}

// ... code from view export UI ...

$view->save();

If the view exists already then I delete it before recreating it.

Then I throw in the code taken from the views export UI, and add right after a $view->save();

And that does it.