drupal 7 user registration custom url returning a blank page I dont think my url is working. I am trying to use page/medical then use the page callback to redirect to medical_reg_form_user_register_form_alter. Instead of displaying the form I get a blank page.

function medical_reg_user_register_menu() {
  $items['page/medical'] = array(
    'page callback' => 'medical_reg_form_user_register_form_alter',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
    );
  return $items;
}

function medical_reg_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#theme'] = 'medical_register';
  $form['actions']['submit']['#value'] = t('Nextdfd');
}

You can't call a hook in hook_menu(). You can either create an alias for the user registration page or replace your menu item with:

function medical_reg_user_register_menu() {
  $items['page/medical'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_register_form'),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
    );
  return $items;
}


Creating comments and nodes with Services 3.x and JSON I'm having trouble getting services to recognize a POST to /comment.json.
I have a similar issue with creating nodes as well.

The following is the error I get:
HTTP/1.1 406 Not Acceptable: Missing required argument comment

This message comes from the file: /services/server/rest_server/includes/RESTServer.inc
Specifically, the lines:

  elseif (!isset($info['optional']) || !$info['optional']) {
    return services_error(t('Missing required argument !arg', array(
      '!arg' => $info['name'],
    )), 406);
  }

basically, it seems to think the "comment" argument is missing (and it's not optional).

This is one of many bits of JSON I've given it (posting a comment to node 8801)

{name:"test",language:"und",cid:"0",pid:"0",uid:"17593",nid:"8801",
comment:{subject:"Subject of the comment, if not entered it will be auto-generated",
comment_body:
{und:[
[{value:"value of the field comment in the comment, remember that in D7 we can create fields for comments too", format: "full_html"}]
]}}}

It's perfectly valid (based on other online JSON checks).  It also matches what I see in the services test examples at /services/test/functional/ServivesResourceCommentTests.test

however, I always get the same error message.
This seems similar to:  Drupal 7 services json node object

which is also unresolved.  Can someone help me with the proper JSON formatting?  Really, all I want to do is pass it something like:

{ nid : 8081 , uid : 17593 ,comment:{comment_body:"test",subject:"test"}}

my http headers seem ok and user/login worked fine.

The following JSON appears to be the minimum you need to post a comment:

{
  "nid":"1",
  "subject":"Comment Subject Text",
  "comment_body":{
    "und":[{
      "value":"Comment body text"
    }]
  }
}

Since there is no user, commenting on this "example.com/node/1" needs to be turned on and permissions for anonymous users to post comments need to be set.


Update all nodes with a default field after adding a new field to the content type I have an existing content type with a number of nodes. I have just added a new boolean field with a default value of "off."

However, until I re-save each node the default value is not set, so a view that should shown only those nodes where the new field is using the default value is currently empty.

How can I update the existing nodes, created before the field has been added, to set that field to its default value?

Sadly, there's no very simple way to do this (besides VBO/rules), but here's the code I use in update functions in my custom module install files when I need to prepopulate field values for a certain node type after adding a new field (in this case, 'page' nodes):

<?php
// Get all nodes of 'page' type, populate the field with a value of '1'.
$pages = db_query("SELECT nid, vid FROM {node} WHERE type = 'page'")->fetchAllAssoc('nid');
foreach ($pages as $nid => $values) {
  $fields = array(
    'entity_type' => 'node',
    'bundle' => 'page',
    'deleted' => 0,
    'entity_id' => $values->nid,
    'revision_id' => $values->vid,
    'language' => LANGUAGE_NONE,
    'delta' => 0,
    'field_page_new_field_value' => 1,
  );
  db_insert('field_data_field_page_new_field')
    ->fields($fields)
    ->execute();
  db_insert('field_revision_field_page_new_field')
    ->fields($fields)
    ->execute();
}
?>

Another manual method mentioned in this answer uses EntityFieldQuery and loads/saves each node. More Drupal-y, but way less performant... (requires a full node load and save operation for each node!).


Where does Drupal set the uploaded file name syntax? I have a file with a filename which has a double underscore in it. When Drupal saves the file, it shortens it to be only one. ie:

  Snapshot__john_doe_2_opt.jpg

When Drupal saves the file, it removes one of the underscores and names it this:

  Snapshot_john_doe_2_opt.jpg

Where does Drupal do this? I need to account for any changes which Drupal makes to the filename and I need to know what other characters it may remove etc.

You can use transliteration module.

and in code use code like

function hook_transliteration_clean_filename_prepare_alter(&$filename, $source_langcode) {
  $filename = drupal_strtolower($filename);
  $filename = str_replace('__','_', $filename);
}

Above code is not tested, Hope it will help you.


How to change the Front page for the Commerce Kickstart distribution? Just that. I changed the front page to "my-front-page". Now if I go to the front page the fields for this node aren't shown at all. Just the blocks are shown.

I guess there is a preprocess function related to the front page. The only one that I see is this one, but nothing happens if I delete this function:

function commerce_kickstart_theme_alpha_preprocess_page(&$vars) {
  if ($vars['is_front']) {
    unset($vars['page']['content']['content']['content']['system_main']);
  }
}

It looks like this preprocess function needs to be changed in the parent theme.

In this case it can be found in the /profiles/commerce_kickstart/themes/omega_kickstart/preprocess folder.


how to find whether a node has more than one revision? How could I find whether a node has more than one revision. I use node_load($nid) and get a $node object.
How can I achieve this using the object? What would be the best way to do it?

Have you checked node_revision_list($node) function?

  This returns a list of all the existing revision numbers.

You can pass the current node and it will return list of all revisions.


Using Slick Carousel with Views - How to setup a slideshow with View I'm trying to setup a slick carousel slideshow. I've created a content type for the images and added a few nodes to the content type with images. I then created a View block...but see no option to format with 'slick carousel'. This article says to choose 'slick carousel' instead of format: unformatted list (but I don't see this option).

The only place I see the ability to choose 'slick carousel' is in the content: image field itself under 'Fields'. But when I choose it there - not surprisingly - it shows no results. If I leave it as the default it shows the images. But, of course, I want not just a block of the images from the nodes but a SLIDESHOW.

Does anyone know how to make this work with Slick Carousel? Thanks.

Note: I have installed the required libraries and the .min.js file

Use the Slick views module.

  Slick views adds a new display style to views called Slick
  carousel. Similar to how you select HTML List or Unformatted
  List as display styles.


Advanced Views Filter I would like to build a view (slideshow) of profiles, which is relatively easy to do. However I would like to filter them based on a node field of the page the view will be displayed on.
I defined a new content type called Category, where I describe categories in more detail. One of the node fields is called category.

My profiles also have a field category. The idea is that when a user views the node Category A, I would like to display a view showing all the profiles belonging to Category A. When the view Category B, I would like to display all the profiles belonging to Category B.

Can this be done via Contextual Filters? If so, how?

I'm not sure if this helps but the Category values are stored in Taxonomy.

Add contextual filter on term id
select Provide default value
select type content id from url
also change your path to [your_path]/%


Views exposed filter: Upcoming/Past events I want to implement an exposed filter in the view with a date field. I want to show two choice in select list according to the date value (upcoming events/past events). But I don't know how to achieve this using date field because it allows to choose date only.
Is there any way to achieve this feature?

Thank you in advance.

Add a date filter.

Expose the date filter.

Select the grouped filters option

Scroll down and define your filters as shown in next image

And you are good to go. You will have an output like this

You can change the options to make it a drop-down too.

To fix for the UI bug in exposed filters groups:

Make sure your date module is at Version: 7.x-2.9 or later, then apply the patch exposed_grouped_filter-1876168-71.patch (https://www.drupal.org/node/1876168#comment-10344663)


Manage programmatically added fields I'm working on a custom module that allow anonymous users who add a new content, to register himself in the same form providing a simple email field (user name is the same as email).

In my module I hook the node_form_alter to add the email field from the user registration form:

function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state) {
  if (\Drupal::currentUser()->isAnonymous()) {

    // Add drupal registration form
    $entity = \Drupal::entityTypeManager()->getStorage('user')->create(array());
    $formObject = \Drupal::entityTypeManager()
      ->getFormObject('user', 'register')
      ->setEntity($entity);
    $user_register_form = \Drupal::formBuilder()->getForm($formObject);

    //kint($user_register_form['account']);
    $form['user_registration'] = $user_register_form['account'];
    unset($form['user_registration']['name']);
  }
}

And this works good.
In node_presave I'm expecting the field to register, but i get an error "Field user_registration is unknown."

function mymodule_node_presave(NodeInterface $node) {
  kint($node);

  $email = $node->get('user_registration')->value; // This throws the error

  if ($email) {
    $email_user = user_load_by_mail($email);

    if (!$email_user) {
      /* Create user */
      $email_user = _create_user($email);
    }

    /* Set user as author */
    if ($email_user) $node->setOwnerId($email_user);
  }
}

What am I missing?

You have to add a custom submit handler to handle these fields. The form fields you add are custom, so they won't be attached to the node.

$form['user_registration']['#submit'] = 'custom_user_registration_handler';

In the submit handler you'll be able create the user like you're doing no in your presave function. The presave function should load the user and attach it to the node.

Edit \

Problem: The node_presave hook does not contain the email adres so it's not able to lookup the right user.

Solution: The default node form has an author form field. You probably hid that field but I think your still able to fill the value. What if you fill the 'author' field with the email value, this will be the user name.

So in your custom submit handler:

Create the user;
Fill the (hidden) author form field with the right value (fill the right value in the form_state object/array?).

The the default form submit handler will do all the hard work for you.


Using modules with almost similar functionality together on production site I have 2 modules with similar/alternative available and I have to use both. Those are Entity Reference and Search API.

Now the situation is that there are few modules which require References and Search modules as a dependency. It is a need and I have to use it.

Can I use all these modules at the same time on a production site?

Is there any possibility of clash or site crash?

Yes, there's always a possibility that modules will be incompatible with other modules that do the same thing.

There's also the possibility that modules whose functionality is completely unrelated will be incompatible with one another. Such is the nature of a modularly extensible system.

The only way you'll know is if:

The documentation for one or more modules list their known issues with other modules, or
You thoroughly test the two modules while both installed on a single site


Saving a unpublished node without validation I have site with a content type that has a large number of fields on it.

I would like to allow users to start to create nodes, but not have to fill out all of the fields in one sitting.  Partially completed nodes don't have to be published, but they do need to be saved in the database.

Is is possible to save the node in an uncompleted state without the validation rules running.  I am mainly interested in required fields not being required, unless the node is published.

When users finish populating nodes, the validation rules should run when the node is published.

Are there any ways to accomplish this workflow?

Another option here is to add a custom validation function to force validation to run, and then also have a custom submit handler to clear any errors produces and save the node.

The code here is mostly taken from this question but this question and this post have also helped.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
    switch($form_id) {
        case 'my_form_id':

            $form['actions']['draft'] = array(
                '#type' => 'submit',
                '#value' => t('Save draft'),
                '#weight' => '9',
                '#submit' => array('save_draft_submit'),
                '#validate' => array('save_draft_validate'),
                '#attributes' => array(
                    'class' => array('cancel'), // add the class cancel will skip any clientside validation
                ),
                //'limit_validation_errors' => array(), // this should be enough to skip validation however does not work for me
            );

            break;
    }
}

function save_draft_validate($form, &$form_state) {
    // Set as unpublished.
    $form_state['values']['status'] = 0;
    // Force validation.
    $errors = &drupal_static('form_set_error', NULL, TRUE);

}

function save_draft_submit($form, &$form_state) {
    // clear error messsages
    drupal_get_messages();
    // save the node
    node_form_submit($form, $form_state);
    $form_state['redirect'] = 'node/'.$form_state['nid'].'/edit';
}


Limiting input on node title and plain text area fields Is there a way to add a character limit on node title and plain textarea fields in Drupal 8? I don't want to use the Title module.

There's the beta version of the Maxlength module which can be applied to built-in fields as well custom text fields.  The Maxlength module allows you to set maximum length of any field; one option includes showing a javascript character countdown on the edit forms next to the applicable fields.

You could also take the js library this module is based off of and apply with the hook_form_alter approach.


How to create node in hook_node_insert without triggering it recursively I have a situation where I need to create node(s) in hook_node_insert for certain dates.

Details: There is a content type with date field (start and end-date enabled). The requirement is to create the node with same contents for those many dates.

For example, if the date is from Mar5, 2014 to Mar8, 2014. I need to create node with Startdate & Enddate: Mar5 for one node and Startdate & Enddate: Mar6 for the next node and so on till Mar8 is assigned as start & enddate for the last node.

I got stuck with infinite loop. How do I solve this?

Why not add a second submit handler using hook_form_alter to the node add form and put your functionality in there as opposed to using hook_node_insert?

That way the code will run everytime the node add form is submitted, but you won't get into the endless loop scenario...


Creating a node with PHP cURL client returns 401 error - X-CSRF token always empty A recent update to Services and Drupal requires a csrf token, and it broke the PHP cURL client samples.

I am trying the sample code for Services to:

Create a node here https://drupal.org/node/1334758
Log in a user here https://drupal.org/node/1491754

It fails with 401 error. $csrf_token is always empty for me, so that should be the problem, but I am not sure how to return it with cURL. Any tips?

I fixed the DrupalREST class by Randall Kent here https://github.com/RandallKent/DrupalREST.PHP/issues/2


Change field from Multi-Value to Single-Value I have a developing a website with a reference term field with multi value. But after the client change the "rules" I need to change the field from multi value to a single value field, but the field as Data, lot's of data.

Is it possible to change from multi value to single value? (the field only as one value inserted and the real object is to use those values).

Use VBO

Introduce a new, single-value field in the bundle, then use Views Bulk Operations (VBO) to copy the data from the old multi-value field to the new single-value.

VBO have an option to "Execute Arbitrary PHP Script" where you can insert a PHP-snippet to do the copying, something like:

$object->field_foo['und'][0]['value'] = $object->field_bar['und'][0][1]['value'];

The PHP above is only an example. Use dsm($object); (requires Devel installed) to figure out the datastructure of the entity object you need to manipulate.

When done, delete the multi-value field.

Alternate solution: Node convert

It is also possible to do bulk conversion with Node convert.

To use this method, you first clone the content type, then change the multi-value field into a single-value field in the clone.  Node Convert let you map content field by field, so you copy most fields directly, and then copy the first value of the multi-value field into its corresponding field.

The disadvantage with this method is that the machine name of the type changes, so you may need to fix that in a number of places if it is used a lot.  The advantage that you can do it all in the GUI, no need to write PHP.


Autocomplete term widget (tagging) - Insert as child Is there a way to insert taxonomy terms as child of a parent term with the auto complete term widget?

I have found several modules such as "Content Taxonomy" or "Hierarchical Term Reference Autocomplete", but couldn't find this specific feature.

I have done some research on this as we use the Autocomplete Deluxe module for our client's sites. Unfortunately I see no preexisting solution and I think you will have to create your own.

This could be quite visually problematical. How do you display this in a auto complete field: Prefixed with all its parents? with a parent attribute type key?

I agree that this could be quite useful as this would eliminate the need to give a non-technical user admin access to taxonomy more and more. But I think this would be better achieved with a custom coded mix of Autocomplete Deluxe and Hierarchical select


How can I create this sort of path structure? Before I go ahead and implement my site's architecture, I'd like to check whether or not it's valid.

I have two taxonomy vocabularies that I want to use as part of my Pathauto settings. My site is a local accommodation guide, so I'd like to implement a URL structure like this:

mywebsite.com/cottages/Whitby/Little-Cottage
mywebsite.com/holidayapartments/Scarborough/Seaside-Apartment

                  ^                 ^             ^
                  |                 |             |----- Accommodation name
                  |                 |------------------- Location name
                  |------------------------------------- Accommodation type

Which follows the syntax mywebsite.com/[accommodation type]/[location]/[accommodation name]

Up until now, I've found it impossible to do this using just taxonomy tokens. I always end up with paths that look wrong.

A way around this seems to be to set each accommodation type as its own content type (for example, 'cottage' content types, 'holiday apartment' content types etc), instead of just having one 'accommodation' content type as I currently have then set the path settings for each content type like so:

Cottage content types: cottages/[termpath-raw]/[titlepath-raw]
Holiday apartment content types: holidayapartments/[termpath-raw]/[titlepath-raw]

Whilst this seems to produce the result I want, it feels more like a compromise than the correct solution. Before I go ahead and do this, I want to check that there isn't another way of setting up the path structure that I want using taxonomy tokens.

I'm also wondering what happens when I introduce multiple vocabularies for those content types - how will I ensure that the location vocabulary doesn't get replaced in the URL structure by another vocabulary (for example, if I use a vocabulary for holiday types - family, group, singles, couples etc - how do I ensure that this vocabulary doesn't take the place of the location vocabulary?).

Okay, I've just had a look at my old test site and I can see that I'm using the following syntax:

[field_locations-term-raw]/[term-raw]/[title-raw]

This displays like so:

/grange-over-sands/holiday-apartments/test-property

The location comes before the page type (accommodation) here, which I'm aware of, but now the path is displayed perfectly! I've previously deactivated the Domain Access module, so I can only assume that it was DA that was causing my paths not to show correctly.

This leaves me with a new question,though, which I'll start separately.


Why does webform configuration not let me choose existing content types I've installed the Webform module and would like it to configure so that I can add a form to a Basic page content. But /admin/config/content/webform does not let me specify any content types. Where is that setting hidden?
Thanks!
EDIT1
What I'm seeing:---------------------------
What I would expect to see:
Why don't I get the choice of the existing content types??

Admin Menu --> Structure --> Content Types --> Basic Page's Edit --> Webform tab --> select Enable

I not sure is this what you mean.


How does Drupal Cron effect Page Cache? I'm trying to figure out how Drupal's cron effects the page cache of my site.  It would be nice to store as many pages in the cache table as possible so that when requests are made they are being served from the page cache!

However I am getting conflicting answers on the effect of Drupal's cron job on the cache!

This link says that "each cron run clears the cache for all pages":

http://tomroelandts.com/articles/how-to-ensure-that-visitors-always-see-cached-pages-in-drupal-7

as well as -> drupal.org/node/1576686

But this guy, says it only clears caches that can be expired:

https://www.drupal.org/node/1691116#comment-6352756

Would love to get a definitive answer on this!

System module's system_cron() clears expirable entries from cache tables. An expirable cache entry is one that is beyond its "can expire" date, or it's an entry that was initially saved with the CACHE_TEMPORARY flag.

Assuming you're using the default database cache, you can see which entries are expirable by looking in a cache table.  The "expire" column contains the timestamp at which an entry becomes expirable. If the value is "-1", it's CACHE_TEMPORARY and always expirable.

As far as Drupal's default database page cache goes, the "expire" column won't tell you much, since the minimum cache lifetime is not applied to the expire value. Instead, Drupal keeps track of the last time the entire cache was flushed, and will not flush the page cache again until at least "minimum cache lifetime" seconds have passed.


What will be the post parameter when specifying vocabulary term? I am trying to create a drupal node with a iphone app via rest server. I want to send the request to drupal as json.

I have added a taxonomy vocabulary for categorizing the nodes. Specifying a category is mandatory when creating node.

  My request url is
  drupal site/ep/node.json

  Post parameters
  node[title]=mysample&node[type]=story&node[body]=sample body&node[???]=myCategory1

I specified title, body, and type....but what will be the parameter name to specify the term of my vocabulary (i.e. category name)?

I tried node[taxonomy], node[term], node[vocabulary], but no success. Please help!

  Config:
  Drupal 6.26
  REST Server 3.0

node[taxonomy][vocabulary term id][tid]=vocabulary term id

in place of vocabulary term id give the term id of the vocabulary term

How to get the term id? I made a custom drupal view of type term where I fetch only the fields term id and term

I then sent the view contents to my iphone app. When I choose a particular term I also have the term id.


Different 'template path' per view? I want to get:

/mytheme-directory
  /front-slides
    /views-view--front-slides--block.tpl.php
    /views-view-unformatted--front-slides--block.tpl.php
    /views-view-fields--front-slides--block.tpl.php
  /front-4-cats
    /views-view--front-4-cats--block.tpl.php
    /views-view-unformatted--front-4-cats--block.tpl.php
    /views-view-fields--front-4-cats--block.tpl.php

instead:

/mytheme-directory
  /views-view--front-slides--block.tpl.php
  /views-view-unformatted--front-slides--block.tpl.php
  /views-view-fields--front-slides--block.tpl.php
  /views-view--front-4-cats--block.tpl.php
  /views-view-unformatted--front-4-cats--block.tpl.php
  /views-view-fields--front-4-cats--block.tpl.php

Can I use different 'template path' or do something else? easy way please :)

Yes, there are instructions for doing this on Drupal.org.

Also, here's a general article on organizing your theme files in Drupal.


"Twig_Error_Loader: Template "file.html.twig" is not defined" for new twig template file After creating a new paragraph type and its template file in the correct folder location, I am receiving the following error every time I view the page with that houses the new paragraph type.

Twig_Error_Loader: Template "file.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "file.html.twig" in the Drupal theme registry.)

I have followed the steps here to disable the cache. However I don't believe it worked because I still have to clear my cache through config>performance for changes to twig files to appear.

Similarly, I tried to enable twig debugging (and turn off caching) here and can not confirm that it has been enabled either.

I found an article: blog.wturrell.co.uk/troubleshooting-drupalcoretemplateloaderthemeregistryloader-unable-to-find-template/ discussing potentially clearing the theme-registry, but I do not have access to drush to run any commands.

I have already tried clearing all the cache from within drupal itself.

Cache is a pretty broad concept, and sometimes mean content caching and sometimes they mean broader things like config settings and the theme registry.  Disabling content caching is still a bit confusing to me so I can't help with that part of the question.

But the theme registry has some pretty simple rules.  If you add new template file (or change it's name or move it to a different folder) or if you add a new theme callback (in hook_theme) or override to a theme callback (hook_preprocess...) then you MUST clear the theme registry before they will be active.  To do that, the simplest method (without additional modules or drush) is to 'Clear all caches' under admin->config->development->performance.

Of note, sometimes the theme registry is referred to as the theme cache.  While I know it's probably possible, I don't think that disabling the theme registry from caching is a standard practice in development.


Bootstrap 3, how disable auto-added Glyphicon? I use Bootstrap (v3) with Drupal 8. When I create a button named "Search something", bootstrap adds automatically a "Search" Glyphicon. I do some web searches, but I don't find how "disable" (or hide?) the 'search'auto-added glyphicon of my button.

When I create a sample submit button from a Form Class custom module :

public function buildForm(array $form, FormStateInterface $form_state) {
...
$form['submit'] = [
  '#type' => 'button',
  '#value' => 'Search something',
];

If I go to the page where there is my form, the button have automatically a magnifying glass glyphicon :

I want display my button without any glyphicon, how can I do that ? I must add a class to my button ? which ?

Thank you !

I haven't tried it for Drupal 8, but its works for drupal 7. It should work for drupal 8 as well.

In your bootstrap theme setting, under bootstrap setting there is tab of General setting. Inside that tab the are settings for different bootstrap components. You will see Buttons there. Just open that section and un-check Iconize Buttons option. That's it.

This will disable all the auto icons in buttons.


Accessing webform status via reference I have a content type that has a reference to a webform. In the template for this content type, I'd like to check if the referenced webform is open or closed to conditionally display some content.

I have a content.field_ballot[0], but this appears to just be a render array without access to the underlying webform settings.

Is it possible to access it through this reference? Or should I be investigating a different route?

Thanks!

You should avoid any complex PHP code in template files.  I recommend you use a THEME_preprocess_node_MY_CONTENT_TYPE(&$vars) hook to perform your checks, then pass a variable to the template file for your basic validation.  In the preprocess function you pass the variable using $vars['my_custom_variable'] = XYZ and in the template you can call the variable with $my_custom_variable.

Make sure Drupal looks for content type node templates, or you can just use the default THEME_preprocess_node(&$vars) and put a check for your content type in there to keep the full validation code from running.
https://www.drupal.org/node/337022

Stackoverflow discussion along similar lines
https://stackoverflow.com/questions/40645297/pass-variable-to-preprocess-node-function-for-use-in-node-template


Drupal 7 WYSIWYG Editor Auto Spell Check My team and I are trying to have the SCAYT (Spell check as you type) feature in the WYSIWYG bar to be automatically enabled, so that we can make our users' jobs easier for them as many of them have requested this. Currently, people are able to enable it in the editor manually. We'd like it so that it's automatically working once they start typing.

I've looked up the TinyMCE module, but it's severely out of date and we won't be using that. I tried to fumble with the code to no avail. I've read different forum but they are all out of date.

Any advice on this would be greatly appreciated and if more information is needed I'll be happy to provide it.

Thanks!

The CKEditor is a very popular Drupal editor that already has a built in SCAYT as you can see here, as well as many other plugins and extensions.


Drupal 7 submit function not called for themed form I am developing a form. 2 functions are:

function reserve_multi_step_form($form, &$form_state)
{
       $module_path = drupal_get_path('module', 'reserve');

       $form['#theme'] = 'reserve_form_2';
       $form["agreed"] = array(
                            '#type' => 'checkbox',
                            '#title' => t("I accept the deposit policy"),
                            '#attributes' => array("onChange" => "policy_accepted();"),
                            );

       $form['submit'] = array(
                       '#type' => 'submit',
                       '#value' => t('Submit'),
                       '#attributes' => array('style' => "padding: 0 10px;"),
                       "#disabled" => true,
                       );

       return $form;
    }

function reserve_multi_step_form_submit($form, &$form_state) {
       print 1111;exit;
}

The theme function:

function reserve_theme($existing, $type, $theme, $path){
   return array(
                'reserve_form_2' => array(
                                          'render element' => 'form',
                                          'template' => 'reserve_form_2',
                                          'path' => drupal_get_path('module', 'reserve'),
                                          ),
}

In the template file I print some text and render the form:

    <?php
    print "text";
    print drupal_render_children($variables["form"]);

The form is displayed correctly. But after I click submit button, the reserve_multi_step_form_submit is not called. Without theming it works. What can be an issue?

You have the #disabled property set on your submit element. Drupal's form API does not process the input for any element, including submit buttons, if the #disabled property is set on the server side.

If you're interested in the code behind this, the decisions are made in the _form_builder_handle_input_element() function in the includes/form.inc file of your Drupal installation.

If you want the submit button to be disabled by default for client-side purposes (i.e. you'll be enabling it through JS based on some action taken by the user) you would be better off setting the disabled attribute directly on the element, as Drupal pays no attention to this when processing the form:

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#attributes' => array(
    'style' => "padding: 0 10px;",
    'disabled' => 'disabled'
  )
);


How to set the values of some fields depending on the value of a list box? Remember the create password page of Drupal! while you are entering characters it tells you how string is your password!

now I want to have something like this in a list box but a bit different. I want to show an image and a text depend on the item which is selected in the list box! How can I do it?

My first try was using conditional field but I have to add 120 image and text field to my content type and but lots of conditions to handle it. It doesn't make sense!

My second try was using markup module but I didn't know how to fetch the value of list box with ajax!

My third try was using entity referenced auto fill but when I select an item from the list box for the first time it fills the other fields correctly. but the next times it does not change any thing.

in addition, I need the image and text field to appear read only (non editable)

Do you know any other way to do that?

Below is a sample of a rule (in Rules export format) that you can use as a prototype to answer your question by using the Rules module:

{ "rules_set_field_value_based_on_value_of_selection_list_field" : {
    "LABEL" : "Set field value based on value of selection list field",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_text" } }
    ],
    "DO" : [
      { "SWITCH" : {
          "USING" : { "data" : [ "node:field-optionlist" ] },
          "DO" : [
            { "CASE" : {
                "USING" : { "value" : "B" },
                "DO" : [
                  { "data_set" : { "data" : [ "node:field-free-format-text" ], "value" : "B.A.S.I.C." } }
                ]
              }
            },
            { "CASE" : {
                "USING" : { "value" : "A" },
                "DO" : [
                  { "data_set" : { "data" : [ "node:field-free-format-text" ], "value" : "A.D.V.A.N.C.E.D." } }
                ]
              }
            }
          ]
        }
      }
    ]
  }
}

Some more details to further explain the above above sample:

The Rules event I'm using is "before saving content".
In my case I have these fields:

a selection list field with machine name field_optionlist.
a text field with machine name field_free_format_text.

The selection list field actually has 3 possible values, like so:

A (=Advanced).
B (=Basic).
C (=Custom).

As a sample, I decided to set the values of the text field like so:

B.A.S.I.C. if "The selection list field's value is Basic".
A.D.V.A.N.C.E.D. if "The selection list field's value is Advanced".
Leave it unchanged if "The selection list field's value is Custom"

Part of the "clue" to make this rule work is the condition Entity has field. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')". I wouldn't be surprised if that is what you are missing in the rules conditions you tried so far ...

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

However, to make the above work, and to be able to get this to work with only 1 rule (instead of writing 2 rules, ie one for "Basic", and one for "Advanced"), I also used the "Conditional Rules module. That way you could expand the above prototype to say dozens of different possible values. For a sample using the Rules Conditional module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

Note: the Field Permissions module should help you to make such text field read only.


System help not rendering in drupal 7 I'm having a problem where my system help block is not properly rendering messages in my main template. It works fine when using my administrative theme, but not in the standard one. When I print_r my $_SESSION variable I get the following:

[fb_devel] => Array
    (
        [FB_OP_POST_INIT] => 280
    )
[batches] => Array
    (
        [90] => 1
    )
[updates_remaining] => Array
    (
    )
[messages] => Array
    (
        [warning] => Array
            (
                [0] => For easier theme development, the theme registry is being rebuilt on every page request. It is extremely important to turn off this feature on production websites.
            )

    )

)

How can I troubleshoot this problem?

Messages are displayed in a block, check that this block is in a region and that region is displayed in your theme.


Views and Filter Criteria - is this normal behavour? Drupal 7 I decided to modify the View after all the content had been uploaded to the site. Now I am experiencing issues with the Filter Criteria, not picking up the nodes which I would expect to be picked up...

Here are the two different sets of Filter criteria I tried:

This View displays 2 search results.

The view above displays 3 results!

Now, what I was expecting is that the first set of filters would display the same number of results (at least) as the filter above. Because, the condition is OR. But that's not the case...

Is this normal behaviour?

I must not be reading the conditional statements correctly, because I am not displaying the results I am expecting...

I think you should change the 2nd AND statement to OR and last OR statement to AND. Looks like everything else is fine.


Drupal Commerce age gate on Add to Basket? I'm building a Drupal Commerce store for a client and some of the products are alcohol which requires me to add a popup modal with some text about age laws when they click "add to cart".

How can I do this? I've seen the 'add to cart confirmation' module but I want to display custom markup and only for certain products. The other projects I've seen are in the sandbox and not well documented on how they are used.

First you can add a popup callback for certain products in the add to cart form alter.

e.g.

function my_module_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
    // if this is the alcohol
    $form['submit']['#ajax'] = array('event' => 'click', 'wrapper' => 'age_check_popup', 'callback' => 'my_module_age_check');
}

function my_module_age_check($form, &$form_state) {
    ctools_include('modal');
    ctools_modal_add_js();
    $commands = array();
    $commands[] = ctools_modal_command_display('title', theme('my_module_age_block'));
    print ajax_render($commands);
    drupal_exit();
}

Then you'll need to handle the clicks in the popup to either add the product or cancel (just close the popup).

You could do this via hook_menu() callbacks or by rendering a form with buttons in the popup.

Edit:

Implement hook_theme() to create a new template file for your popup content.

e.g.

function my_module_theme($existing, $type, $theme, $path) {
    return array(
       'my_module_age_block' => array(
          'template' => 'my_module_age_block'
        ),
     );
 }

Then add a template file my_module_age_block.tpl.php and put your HTML content in here.


Make node a revision of another node I have migrated content from a non-Drupal system to a fresh Drupal site. Some of the content nodes however should in fact be revisions of another node, not a unique node of themselves.  Is there any quick and easy way to turn a node into a revision of another node?

I have not come across such a scenario. However, here's a fairly simple method to achieve it:

Install the Entity Reference module
Add an Entity Reference field to the content type of this node by navigating to Structure > Content Type > [the content type of these nodes] > Manage Fields
Choose the Target type as 'Node' & choose the same content type as the 'bundle'
Label this field as 'Revision of' (say)
Now, you can either choose to manually enter the 'nid' of the original node here or run a query in the database to fill this entity reference field with the nid of the original node.
For example, lets say the content type is 'test' & the entity reference field is 'field_revision_of'

6.a. Write an insert query like this:
   insert into 'field_data_field_revision_of' set entity_type = 'node',bundle='test',deleted=0,entity_id = [nid of revision node],revision_id = [nid of revision node],language='und',delta=0,field_revision_of_target_id=[nid of original node];

6.b. Since you should also update the database revision table of a field:
 insert into 'field_revision_field_revision_of' set entity_type = 'node',bundle='test',deleted=0,entity_id = [nid of revision node],revision_id = [nid of revision node],language='und',delta=0,field_revision_of_target_id=[nid of original node];

Let me know if this helps.

Regards,

Supriya Rajgopal


How to copy field value into another field by its node ID? I have a document that goes through 3 phases.  Each phase is its own content type because each phase brings in new questions and structure built upon the previous phase.

I want the below to happen when a user is adding new content for phase 2 & 3:

User is asked for node ID of previous document in phase 1
Field values from that previous node is retrieved and imported automatically into the new content's fields.

Are there any existing modules that can do this?  Maybe the Rules module?

I could not find a solution to my problem, but I found a workaround.  Instead of 3 phases with each their own content types, I instead was able to make one content type and use the vertical tabs to create 3 "sections".  It is not ideal but it should work.  I would still like to know if what I am asking is possible.


Limit node.js updates if the view is active I have a Facebook style news feed view which updates via node.js and rules when new content is created. This all works fine however if one user is in the process of commenting on a node teaser (comments shown on node teasers on the view) and another user creates a new node, the view then updates causing the unfinished comment to be lost.

My question is: is there a way to restrict the node.js view update for the current user if the view is currently active?

I had and just have the same problem with node.js views update. It seems that the module is refreshing every view that's in use.

I managed to get a workaround by styling my news feed with an open comment section. But i think this is only a solution when you do not expect a hughe amount of comments.

In another use case I implemented another workaround with jQuery:

On my page users can create requests and other users are able to answer these request. A request is a node type and an answer is a node type. They are connected through entity reference module and i wanted to have some sort of inbox functionality where every answer to a specific request is shown in a menu on the specific request page. A user could then click on a answer-menu-item and the whole answer is shown under the request. To give it a more chat feeling I implemented the comment form of the specific answer and styled it to look like a chat form.

This is done with two views implemented on that page. The menu functionality is done with jQuery (Click on menu item -> show related views row of second view). With node.js views refresh I managed to get the chat feeling (When a new comment is added -> refresh first and second view).

I then ran into the same issue like you described above. Each time a user submitted a new comment both views refreshed but the views returned to the their output states - for example: the user was reading an answer of user G and was commenting on that answer when the view was refreshing because of a new comment on an answer of user Y. The view returned to its output state and was not showing any answer because they were initially hidden to achieve the inbox / menu functionality.

My workaround for that problem is:

var content = [the views-row belonging to the menu entry]
$(specific-menu-item).click(function(e){
    $(".my-second-view .views-row").hide();
    $(content).show();
    Cookies.set('latest-viewed-answer', content);
    return false;
    e.preventDefault();
});

$(document).ajaxComplete(function() {
  var latest = Cookies.get('latestmessage');
  $(".my-second-view .views-row").hide();
  $(latest).show();
});

To get the Cookie thing working https://github.com/js-cookie/js-cookie

Sorry for my long answer, but i thought that it would be necessary to understand my needs to understand my workaround...

Because this is still a workaround and because I'm asking myself if there will be performance and server issues with our approaches (news feed and chat) I would love to see a solution that is really solving the problem.


What is the parameter $instance_id in the function Block::setVisibilityConfig? I need to programatically set the visibility of a block. I've loaded the block, and I know I need to use the Block::setVisibilityConfig method, but I don't know what the $instance_id variable is.

Does anyone know what to pass here to the function?

I got it. Example:

use Drupal\block\Entity\Block;

function mytheme_preprocess_html(&$variables)
{
    $block = Block::load('sitebranding');
    $block->setRegion('content');

    $visibility = $block->getVisibility();

    if (isset($visibility['request_path']['pages']))
    {
       unset($visibility['request_path']['pages']);
       $visibility['request_path']['negate'] = 0;
       // $visibility['request_path']['pages'] = '/node/2';
       $visibility['request_path']['pages'] = \Drupal::config('mymodule.settings')->get('services_block_path_visibility');
       $block->setVisibilityConfig('request_path', $visibility['request_path']);
       $block->save();
    }
}


Filter data from two content types with different criteria in view I've got these two content types, A and B. It's pretty straightforward to set up and display them in the same view. However, I can't get them filtered. I've added two filters rules, one for each content types, a1 and b1 respectively, in the hope that I can extract the right parts of the data from A and B and show them in my view. But that doesn't work out.

//
a1=published and content type A and category=aa
b1=published and content type B and tag=bb
//

Here is what I got while trying to do so:

no rules at all,
view displays all the stuff from A and B
rule a1,
view displays A only
rule b1,
view displays B only
rule a1 or b1,
shows nothing

filter groups i used

Is there anything wrong or filter criteria can only be applied?
Any help is appreciated.

--update 1--
I did some more experiments about grouping filter criteria:

 - case 1
Content: Published (Yes)  AND
Content: Type (= Portfolio)
OR
Content: Published (Yes)  AND
Content: Type (= Blog entry)  AND
Content: Tags (= frontpage) | Settings
 - case 2
Content: Published (Yes)  AND
Content: Type (= Portfolio)
Content: Tags (= frontpage) | Settings
OR
Content: Published (Yes)  AND
Content: Type (= Blog entry)  AND

"Content: Tags" is a unique field which only appears in content type "Blog entry" . To my surprise, case 1 and 2 will yield the same result, blog entries, even though "Content: Tags" has nothing to do with the content type "portfolio".

--update 2--
a bug?
Incorrect filter group OR behavior

a1 and b1 will show nothing, because content type == A AND content type == B is always false for 'A != B'

On filter block, you have a drop down with options. You need to group them into groups connected with OR, so you will have:

published and ( (content type == A and category == aa) or (content type == B and tag == bb ) )


Index isn't crawling paragraph fields I have the following index and paragraph fields checked off as my paragraph field is called field_content. However when I do a search for something inside these paragraph fields. I'm not getting any results.

Is there a way to debug if it indeed is crawling my paragraph fields? Or is there another setting that I might be missing since I'm attaching the paragraph entity to the Basic Page content type. Does Search API even go into the sub-entity and crawl that aswell?

Aside from just checking off those boxes on the search api page, you have to also mark it in the View exposed filter that your creating as seen below:


How can I control access to group-private content based on organic groups roles? I would like my groups to be able to create content that is not only private to a group, but also private to certain roles within the group. For example, a post that is only accessible by members of Group A that also have the "officer" role.

Ideally, I'd be able to make the roles group-specific because different groups should be able to create and assign roles to their members.

How can this be accomplished?

I needed somewhat similar functionality for a drupal 6 site and gave up on using OG for this.
Instead I made a vocabulary that defined my groups and used tac_lite for setting access.
The setup is being ported to drupal 7 right now, and I haven't had any problems implementing the same functionality in d7 so far.
Maybe tac_lite is a solution for you? http://drupal.org/project/tac_lite


Possible side effects when changing node type? I sometimes have uses cases where I want to be able to change the type of a node.
There is a nodetype module that comes with a big disclaimer: "only use if you know what you are doing".

Of course I would lose any fields if they have a different name with the other type. What else could go wrong?

Would it be save to use node_load(), modify the type and then use node_save()?

I've changed the content type of nodes directly in the database plenty of times and the only thing I've had to deal with is orphaned field data for nodes.

I think that this orphaned data might cause some false-positive results for certain query types (EntityFieldQuery springs to mind) but I can't be absolutely sure.

Instead of risk this I've always written a small script to go through the field tables in question and clear up any stagnant data after I've made the content type change.

I don't think you'll encounter any errors using node_load() and node_save() as you suggest; it would probably be wise to clear Drupal's cache once you've made the change in case anything needs to be updated there.


Using drush when database and web server are separate I am having trouble using drush on server setups where the web (111.11.11.1) and database (222.22.22.2) servers are separate.

drush sql-connect

gives me the correct output of

mysql --user=mysite_user --password=abcdef12345 --database=mysite --host=222.22.22.2

If i type this into the console of the web server it connects me to the mysql on the database server correctly, however...

Running

drush cc all --debug

results in the following messages

Executing: mysql --defaults-extra-file=/tmp/drush_j4KBOf --database=mysite --host=222.22.22.2 --silent  < /tmp/drush_xpMPoI
  ERROR 1045 (28000): Access denied for user 'root'@'111.11.11.1' (using password: YES)

It looks like drush is trying to connect using a different set of credentials and failing, i cannot find any my.conf where db credentials are hardcoded.

The user name is taken from root's .my.cnf file (normally located in /root/.my.cnf. Either remove the user line from that file, or run Drush as another user than root (which might not have a .my.cnf file.)

Added: The relevant part of the MySQL documentation:

  If multiple instances of a given option are found, the last instance
  takes precedence, with one exception: For mysqld, the first instance
  of the --user option is used as a security precaution, to prevent a
  user specified in an option file from being overridden on the command
  line.


Creating media_bundle entities programatically I am still trying to wrap my head around some of the D8 things.  Working with some media bundles like media_audio_bundle and need to write some migration scripts. I have spent couple of days now researching and trying everything but nothing seems to work.

Its like Drupal wall all over again.

This is the closest I came:

$audio = \Drupal::entityTypeManager()
          ->getStorage('media_bundle')
          ->create(array(
            'type' => 'media',
            'bundle' => 'audio',
            'title' => 'Another Audio',
            'field_audio_file' => 11
          ));

It seems to create some sort of media object but does not save it.

If somebody can help, would be much appreciated.

use Drupal\media_entity\Entity\Media;

$image_data = file_get_contents("URL OF FILE");
$file_image = file_save_data($image_data, 'public://FILENAME', FILE_EXISTS_REPLACE);
$media_image = Media::create([
  'bundle' => 'image',(YOUR BUNDLE)
  'name' => "FILENAME",
  'field_image' => [
    'target_id' => $file_image->id(),
  ],
]);
$media_image->save();

Try this one, maybe this will help.


How to remove the top, bottom, left... region when theming a node in Drupal 6 After some revise on the template.php, I can theme a node with specific content type. However, could I remove the default region such as header, footer to make it likes a blank page?

I think You need to create specific page.tpl.php for your content and don't include these regions in the template. You name them page--YOUR_CONTENT_TYPE_MACHINE_NAME.tpl.php according to this thread. You can also try this module


User menu tab content On the /user page i've created two tabs:

function hook_menu() {

    $items['user/%/My-Courses'] = array(
        'title' => 'My Courses',
        'type' => MENU_LOCAL_TASK,
        'page callback' => 'drupal_get_form',
        'page arguments' => array('hook_form'),
        'access callback' => 'hook_access',
        'access arguments' => array('access content'),
    );

    $items['user/%/Privacy-Statement'] = array(
        'title' => 'Privacy Statement',
        'type' => MENU_LOCAL_TASK,
        'page callback' => 'drupal_get_form',
        'page arguments' => array('hook_form'),
        'access callback' => 'hook_access',
        'access arguments' => array('access content'),
    );

    return $items;
}

What i'm trying to do is add a link to the my courses tab, and a privacy statement (just text) to the privacy statement tab.

function hook_form(){

$form['privacy'] = array(
    '#type' => 'textfield',
    '#value' => 'Privacy statement',
  );

 // returns whatever you want to appear in that tab.
 $form['link1'] = array(
     '#type' => 'submit',
     '#value' => t('This will show the customers courses.'),
 );

 return $form;
}

The problem is that it's adding both the link and statement to both tabs.

How would I go about targeting each tab individually?

I think you'd be better off creating 2 separate forms for each tab, but if you want one form to handle both you can use the function menu_get_item() to determine the menu path that routed to the form.

  $menu_item = menu_get_item();
  if(isset($menu_item['path']) && $menu_item['path'] == 'user/%/Privacy-Statement') {
    //@TODO: Add form elements specific to privacy tab
  }


Is it possible in Drupal Commerce to have 2 price fields according to role? Is it possible to have 2 price fields, with manually added price?

Currently I have second price calculated. User with role "EUR_price" will see only EUR prices and others + anonymous will see USD. And this for product, in cart, order etc.

I'm not sure, if Rules (and separate price field) is enough for this.

Are you looking to have a different price depending on the role of the user? If you want to have a price based on user role then the Commerce Pricelist module can help with that.

From the module list

  Different prices for different roles or individual users

  Different prices for different quantities

  Different prices based on order date (like a time-limited discount)


Trusted_host_patterns not working with domain I'm working with a drupal 8 site and trying to get trusted_host_patterns working properly with the domain that I'm using, and no matter what combination of regex I try I can only get it to work with the catch-all '^.*$'. So far, I've used (plus a couple more):

'^production\.sitename\.com$',
'^www\.production\.sitename\.com$',
'^.+.production.sitename.com.$',   // which I know is the same but more general than above

which as far as I know from looking at examples, should work. Is there anything I'm missing?

Figured this one out after some trial and error. I don't know if it is necessary due to some server settings I have, but I fixed this by adding the private IP of my server to the trusted host names setting. I'm uncertain as to why this is necessary since all the other examples I've seen don't need any reference to the private IP, but in my case it seems to be needed.


What Multiple contributors means in Drupal Translations site? I just notice that when you go to the different Drupal Translations sites (for example the French site) there is a user named Multiple contributors but I can't figure out what this means, is a user or a contribution that is made from a different site?

See the Working with translation files offline documentation under the Contributing back to the community header:

  When you have finished, contribute the translation back to
  localize.drupal.org by importing the file on the translation team user
  interface. Translations will either be attributed to you or "Multiple
  contributors" depending on which option you choose. "Multiple
  contributors" is a special account you can use if multiple people
  worked on the translations being imported and singling out one
  contributor for attribution would not be correct.


How to exclude an external js from a particular node? How can we remove an external js from a particular node!

For Ex:
Remove http://cdn.jquerytools.org/1.2.6/jquery.tools.min.js from home page.

If the script is added in a correct way(using Drupal API) you should be able to unset it as following:

Drupal 7:

/**
 * Implements HOOK_js_alter().
 *
 * @param $js
 */
function HOOK_js_alter(&$js) {

  $node = menu_get_object();
  if (!empty($node->nid) && $node->nid == XXX) {
    unset($js['your_path']);
  }

}

Drupal 8:

/**
 * Implements HOOK_page_attachments_alte().
 *
 * @param $attachments
 */
function HOOK_page_attachments_alter(&$attachments) {
  /** @var \Drupal\node\NodeInterface $source */
  $node = \Drupal::routeMatch()->getParameter('node');

  if ($node instanceof \Drupal\node\NodeInterface && $node->id() == XXX) {
    unset($attachments['your_js_path']);
  }
}


Add meta data to menu items I have a Drupal website where many custom modules are implemented. These modules create custom rendered pages which are linked to menu items. This way a menu item represents a custom rendered page. Some other menu items are linked to node instances.

My goal is to provide meta data to each of these menu items. The meta data I want to add to each menu item are 'page description', 'user notes' and eventually term references (taxonomy).

Is there a way to add meta data to each of my menu items?

One possible solution I can come up with is creating a content type that wraps custom rendered pages with a 'description', 'user notes' and 'tags' field. Then I would create a node for each of my custom rendered pages and link the nodes to the menu items. But I'm wondering if there aren't more elegant solutions..

Use Menu attributes module. The module currently allows you to set the following attributes for each menu item:

Id
Name
Target
Rel
Class
Style
Accesskey


Backup_Migrate Module able to Create Backups but NOT Restore them Using Drupal 7.37, Omega4-SubTheme
Acquia Dev-Desktop Stack (Development)
Windows 7 HP
Using Backup_Migrate-3.1.

I set up my Backup and Migrate settings to back up my entire website-code and the corresponding Database.

This is set to copy the Backup to a subfolder in my C:\ Folder directory.

Back up and Migrate saves the Backups fine and I can see them when I navigate to my Backup-Folder.

They are saved as Zipped-Files.

If I try to restore using one of my Backups, I get an error (next item).

Exception: Unable to create directory 'C:\Drupal-Temporary/backup_migrate_556bb93614fe3/docroot/C:' in Archive_Tar->_error() (line 635 of C:\Users\Chandra Swa\Sites\drupal-7\modules\system\system.tar.inc).

There appears to be some problem in reading a "Temporary" directory, not my actual saved Backup directory.

What is causing this error; what does it even mean; is there a fix?

Thank you for your time to read this.  I have tried to be as thorough as possible.

Please try with the Patch mentioned on following URL:
https://www.drupal.org/node/2320969#comment-9564267

Patch for make full site restore (and full site backup) work on Windows. The main
problem was in assumption that directory separator is always '/' but that's not true on Win. So wherever i've found '/' in operation on paths i've changed them to DIRECTORY_SEPARATOR constant.

Thanks!


Problem in admin login, showing blank page in drupal 7? Problem in login admin part.

Whenever I try to click on login link or try to login directly from homepage. It shows white screen. Which type of problem is this. I can't see the error logs due to problem in admin login.

Is this issue due to low server space ?

After RND I found that "WSOD" or "Page not found" error occurred due to two reason.

Either Clean URL  is disable : If we want to check that Clean URL is enable or not then in URL "/?q=user/login" add this, if page shown it mean that Clean URL is disable.
Cache not clear : If your login page is working properly then login through admin & clear Cache.

NOTE : After work on admin part try to log-out a/c. Sometimes due to this reason some unconditionally error occured.


Custom content type add form I am brand new working with Drupal 7 and I am working on a professional project and I would like some help to achieve some requirements.

We have some content types like associations. Authenticated users may add new associations after administrators validation.
What is the best approach to display custom forms that are able to insert data as content types?
This forms must appear in a non administrative environment, so, I don't know if there is something to export Drupal add/content form and display it to the authenticated user.

I will appreciate any help.
Cheers!

Any administration page such as /node/add will be displayed in the selected theme, as long as the user has the permission 'View the administration theme' off (and of course has the relevant permission on, such as to create nodes for the specific type).

You wouldn't really need to create a custom form for that, the standard node create form may be sufficient. Of course you could, you would have to read the documentation such as this.

As far as the first requirement about validation from administrators, the modules Workflow and/or Rules would be useful.


can you search database for page values I have taken over a Drupal 7 site which used to be on a different server and has now moved to ours. I have discovered that on lots of Pages, there are images which point to the wrong server name, the name being hard coded on the page. To save me having to load up each page to test (there are 1000's of them), I thought I could search the database for the value I wish to change. I can see page information is stored in the node table but thats just the page title, created at, type etc. Which table is the text on the page stored in?
I have checked the settings.php file and the correct server name is in there.  If I edit a page, I can see the html for the images that don't show on the page point to a completely different server

Here's a SQL-centric explainer: each field in Drupal 7 has two storage tables associated with it:

field_data_{name-of-field}
field_revision_{name-of-field}

In both cases, the field contents will be in a column like {name-of-field}_value. You can run a MYSQL UPDATE with a REPLACE function to bulk update URLs in these tables.
So if you find that the text you need to update is in the 'field_body' table:
UPDATE field_data_field_body SET field_body_value = REPLACE(field_body_value, 'oldurl.com', 'newurl.com');
UPDATE field_revision_field_body SET field_body_value = REPLACE(field_body_value, 'oldurl.com', 'newurl.com');

Immediately after running these queries, you must clear the Drupal cache. This is best done from the "Performance" admin page in the Drupal UI. If you insist on SQL-only remedies, you can clear the particular relevant cache with this:
TRUNCATE TABLE cache_field;

The regular caveats apply:

Have a backup of your database ready, and verify that the backup you have restores correctly!
Be judicious about your REPLACE functions, that you don't accidentally replace more than what you thought you were targeting.
Yes, you should perform the REPLACE against both the data and the revision tables.


migrate import image (image_import plugin doesn't existe) I'm trying to import content from a csv source file, the csv file contains a field of image URL, and I'm trying to import that image using contrib modules migrate_plus, migrate_source_csv, migrate_tools.

Here is my configuration YAML file:

id: my_csv_import
label: Import test
migration_groups:
  - ACME import

source:
  plugin: csv
  # Full path to the file.
  path: 'news.csv'
  # Column delimiter. Comma (,) by default.
  delimiter: ','
  # Field enclosure. Double quotation marks (") by default.
  enclosure: '"'
  # The number of rows at the beginning which are not data.
  header_row_count: 1
  # The column(s) to use as a key. Each column specified will
  # create an index in the migration table and too many columns
  # may throw an index size error.
  keys:
    - Title

  constants:
    file_destination: 'public://images/'

process:
  title: Titre
  field_image:
    plugin: image_import
    source: Image
    destination: 'constants/file_destination'
    title: file_title
    alt: !title
  type:
    plugin: default_value
    default_value: posts

destination:
  plugin: entity:node

CSV file:

Titre,Image
title 1, http://my_domaine.com/images/image1.jpg
title 2, http://my_domaine.com/images/image2.jpg

Question:
While executing the command line drush mim my_csv_import drush return the following error message:

Drupal\Component\Plugin\Exception\PluginNotFoundException: The "image_import" plugin does not exist. in                                        [error]
/Users/brahim/void/Sites/news8/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php:52

Any help is appreciated!

Solved by installing and enabling the contrib module migrate_file


Path for images inside a block Right now I'm at "http://localhost:8080/drupal/xxxx/user/password" and I added an image inside a block like this "sites/default/files/background.jpg"

But I think is wrong because I'm at 2 paths "user/password" and it is not taken my images, in which way can I write the path to access to my images???

You can display image using following URL:

/drupal/xxxx/sites/default/files/background.jpg

This is for your local setup. While migrating your drupal setup to production at root directory, your image url will break, because of directory change. To avoid this, you will need to change the path of image as below:

/sites/default/files/background.jpg

You can fix this broken your without changing the URL at production by using Pathologic. After Installing this module, you will need to enable Pathologic filter by checking Correct URLs with Pathologic in Text Formats e.g Full HTML. Then select Correct URLs with Pathologic tab from vertical tabs & Path relative to server root (/foo/bar) radio option. Add following values in the text area & save.

/drupal/xxxx/
/


Get node alias in template I create a about-us with Basic Page content type, and with path alias aliased it to \about-us( nid = 2),Now in template file I want to get path alias

{{ 'About Us'|t }}

in Drupal 7 I got it with  url("node/2") but what is equivalent in Drupal 8?
what snippet  I have to use to get path alias of nid 2 in template  file ?

You can use path('entity.node.canonical', {'node': dd.nid}) in the template file.

The markup in the template file would look like this.

{{ 'About Us'|t }}

I haven't tried it, but it should work.


How to set up a Drupal 7 forum I have installed the core Forum module in Drupal 7.  When I go to:

http://www.mysite.com/?q=forum

The forum list is displayed, however the links that allow me to post are not being displayed.

I'm surprised that I haven't been able to find a tutorial on the net on how to set up a Drupal 7 forum.

What am I doing wrong?

Your theme is probably not presenting the new action links in D7. In a default install of D7 and forum (using Bartik theme) I can see them. See http://definitivedrupal.org/suggestions/action-links for an explanation.


Globally providing title attribute to links Recently I've been asked by a SEO-managing person to copy the text of all links within main menu into their title attribute. As my menu is run by OM Maximenu and contains mostly Views, it was relatively easy to add it in corresponding view, but I started to wonder if there's a way to globally alter links in such a way. It would have to be performed in PHP level (template.php or a module). I haven't found a hook though like "drupal_link_alter", except for some old Drupal 5 function?

Any insights?

A lot of links end up going through theme_link() at some point (even those that go through the l() function by default); so providing a preprocess function for that theme, that adds a title to any link that doesn't already have one, would be a very good start:

function MYTHEME_preprocess_link(&$vars) {
  // If there is already a title set, and it's not empty, we don't need to continue.
  if (isset($vars['options']['attributes']['title']) && !empty($vars['options']['attributes']['title'])) {
    return;
  }

  // Otherwise we use the link text as the title.
  $vars['options']['attributes']['title'] = strip_tags($vars['text']);
}

This won't catch links that are outputted directly in HTML, or don't go through l()/theme_link(), but I think you'll struggle to intercept those anyway (it would require some DOM parsing or ugly regex).


Views - user/role has access to edit node I'm trying to set a view that shows only the nodes that current user or role has access to edit. I've tried with contextual filters and relationships but with no luck. Anyone know how to restrict it?

Views accessed can be controlled by Views Access configuration, check the screen shots if it helps.

Step 1: Find the Views Access Configuration

Step 2 : Opt the permissions, which suit your needs

Step 3 : Configure the permissions


How to use php filter for "contact page" in drupal 6? How can I set the PHP filter for the "contact page" in Drupal 6?
I want to insert some PHP code in the description of the contact form page.
Thanks

If your want to enable php code filter for user end, it could be dangrous for your site.
Any one can perform some dangerous activity by adding php code.
or if you want to alter the "contact form" then you have to use  "hook_form_alter".


Why is my text hyphenated? I have a text field. When I enter text in the CKEditor the words look OK. But when I look at the rendered page, it seems as if Drupal has split all word instead of put the entire word in the next line.

For example the word "Materialien" in the screenshot is split and this is not correct. I tried the CSS word-break property, but it seems that something is coming from Drupal and is breaking all the words.

There's some hyphenation library on your page. That's no default Drupal behavior. Find that library and remove it or make it ignore your body fields. Probably some JS library.

OP found hyphenator.js inside MYTHEME/vendor/hyphenator.js.

To remove the library, find out where it got added to the site. drupal_add_js() in D7, or some MYTHEME.libraries.yml library declaration in D8. Or just from the theme's info file.

I'd recommend to fix the hyphenation and simply exclude it for certain fields. This probably can be done with only a few lines of custom JS. Find out how by visiting the docs of that library from the link above.


Redirect to anchor after form validation in Drupal 6 I am trying to redirect user to anchor of error form field after form validation.

I have such form and:

$form['#validate'] = 'my_form_validate';

Then, in validation function, if the form has some error message I am trying to scroll to error field:

function my_form_validate() {
    ...
    $form_state['redirect'] = 'node/'.$form['nid']['#value'].'#'.$error_field_anchor;
    ...
}

But my form is not redirecting after validation.

I have tried  another paths such as: user/1, node/123 without anchor but form is not getting redirected to that one.

Use this and put in you form

$form_state['redirect'] = 'url';


Is there any module for picking photos for image field on mobile platforms like iphone I think this is probably impossible but I wondered if there was any way to provide image upload or equivalent for mobile platforms for drupal.

No, you'll need to write an iphone application to do the photo upload (using a web service).

There is an older post with more info.

With Android phones the regular photo upload works, at least that's what I heard from a couple of users.


New multisite server: should I use CPanel? And Symlinks? I'm commissioning a new server to host a mix of D6 and D7 sites.

My old server had Plesk, which was a bad idea for Drupal, as I spent most of my time trying to get around its security to allow a multisite configuration to work.

The first question I have is whether to install CPanel or manage the site through the command line?

My second question is a bit more involved.

Currently I structure my Drupal setup as follows:

/var/www/drupal/drupal-7.26 (Current Drupal version)

/var/www/drupal/drupal7 (Vhost points here - Symlink to drupal current version)

/var/www/drupal/sites7 (Drupal sites directory - keeps it separate from the current drupal version)

/var/www/drupal/drupal-7.26/sites (Symlink to above sites7 directory)

I've found that keeping the sites directory separate from the Drupal install directory helps when upgrading the core Drupal version, but it does seem to break the ability to use D7's module upgrading.

Any thoughts on whether it's worth sticking with this structure, or should I switch to plain directories?

Thanks,

James

From the information you've provided, it sounds like CPanel would not be a good setup for you. CPanel is great if you want an easy way to manage separate accounts that don't have access to each other. That's why many resellers use CPanel. You will likely spend just as much time getting around CPanel to do what you want.

However, keep in mind that CPanel offers a lot out of the box, like email, easy SSL Cert management, DNS management, and monitoring, not to mention security and software updates. If you spin up your own environment, you will need to make sure you set up a firewall of some sort, and an email server, at the very least. Server setup can be a large topic, and is very dependent on your particular hosting needs.

You didn't mention it, but have you looked at Aegir? It may provide you with the multi-site management and update management that you're looking for: http://www.aegirproject.org/

Regarding your proposed directory structure, I have not tested a setup like that so I can't provide a direct answer to your question, but I would look into using Drush and aliases if you haven't already.


Add field formatter settings to all field formats I would like to be able to modify the display of any field formatter. To to this I think the best approach is to add settings to all field display formats. Alternatively, I could create my own field formatter that applies to all field types and then show the default display formats within my own display settings.

For example say I want to have a field display settings checkbox that enables a div around the display of any field.

I've managed to work this out.

hook_field_formatter_info_alter() isn't properly implemented in Drupal 7. There is however the field_formatter_settings module which exposes two hooks:

hook_field_formatter_settings_form_alter()
hook_field_formatter_settings_summary_alter()

https://drupal.org/project/field_formatter_settings

Using the dependent modules (e.g. field_delimiter) as examples I was able to achieve what I needed.


How to customize a contributed module's template I have a contributed module with a theme file in the module's directory. I want to change it a bit by creating a template file in my custom theme directory. I thought I could just copy and paste the template file into the directory and it would be overridden. That doesn't work, so what am I missing?

Here is the implementation of hook_theme() that's in the .module file:

function wunderground_api_theme() {
  return array(
    'wunderground_api_block' => array(
      'template' => 'wunderground_block',
      'variables' => array(
        'weather_data' => NULL,
      ),
    ),
  );
}

To apply changes in templates, you must first rebuild Drupal's theme registry.

Navigate to /admin/config/development/performance and click on "Clear all caches" button.


Blank window when i press select media link I have created a video content type, created a video field, and used media asset.
When I create a video node and click on "Select media," a blank popup shows up. In this blank popup, I have to choose in which way to upload file.

In the Firefox error console I see the following error:

  TypeError: this.contentWindow.Drupal.media is undefined

I am using Drupal 7.20 and the latest version of the Media module.

Use Firebug or Chrome Developer tools and look at the "Network traffic" and "Console" windows. I'll bet your getting a 404 or a JS related error in 1 of those windows.

You can then correct your server file permissions, fix the JS code error, or whatever.

You dont just have a blank page -- you have a blank page and an error reported somewhere.


Admin Menu Permissions I want to allow my editors to add taxonomy terms to vocabularies. But to do so, I need to give them the permission "Use the administration pages and help", but as soon as i do that, they also can see the menu item "Configuration" in addition to the menu item "Structure".

How can I avoid that?

The taxonomy fact was just an example. I also need this for webforms, so it would be better to have a general solution for that then just for a single module since this problem will occure for every configuration that is stored below "Structure".

It got this fixed using: Admin Links Access Filter


Drush custom command not found in context of running --root option Drush 8. Have the custom module with the custom command.

Call drush custom-command works as expected.

Call drush --root=sites/subsite custom-command thiggers the error:

The drush command 'custom-command' could not be found.

How to call the drush command in the context of the subsite?

To call a command on a certain instance of a multisite you are supposed to pass the -l option. Also be sure that the custom module that provides the custom command is enabled on the multisite instance you are trying to call that command on.

$ drush custom-command -l subsite


Render fields url in tpl.php I have a content type (music) with fields(image,track,title). I used a soundmanager player to display my track with its tpl.php(bar.tpl.php).

I have tried to display url of the image field inside the (bar.tpl.php) but got only (http://localhost/mysite) using this code

 <img src="<?php $file = file_load($node->field_image_boss['und'][0]['fid']);
  print file_create_url($file->uri); ?>" />

I use IMAGE URL FORMATTER module

Then on view's, click on your field, for formatter you can select Image URL.

Then on your tpl.php file use <?php print $fields["field_image_boss"]->content; ?>

Note if you see that your field gets printed with extra markup such as url instead of just url. Then you need to remove extra views container markups

On your view's edit page. Under Format click on the 1st settings and uncheck  Add views row classes and Add striping (odd/even), first/last row classes

Also, on the 2nd settings, uncheck Provide default field wrapper elements

Lastly, click on your field, and under STYLES SETTINGS make sure everything is unchecked


FAPI 'radios' don't respect '#default_value'? I noticed that the 'comment settings' radio buttons ('#type' => 'radios') were not respecting their default value settings in my content types.

I have several module created custom content types, as well as the normal 'Page' and 'Book' content types in this D6 installation, and all of my custom content type's node forms are appearing with apparently random values for their default values.

Repeated loads of the same node form shows different default values for 'comment settings' every time. Looking at the $form arrays for my content types and comparing them against the $form array for a Page content type I only saw one difference: the use of the '#parent' element; I added to my logic (as shown below) but it makes no difference.

I noticed this while trying to create a 'radios' form element for a non-node creation form. Here's some logic I'm using that should give me a consistent default value, but does not:

$form['radios-test'] =
    array( '#type'          => 'radios',
           '#parents'       => array('radios-test'),
           '#title'         => '',
           '#default_value' => 0,
           '#options'       => array(t('first'), t('second'), t('third')),
           '#description'   => 'explainer text goes here',
         );

What am I missing here?

Your code works fine at my end, I always get "first" selected on repeated page refresh. Can you copy paste your actual code that is showing different value for comment settings? Maybe something else is interfering. Can you paste your code at one of the pastebins - http://pastebin.com/ ?

Below is a screenshot at my end.


On hook_form_alter setting select list options for a field By default select options i have left empty in admin of that content type.

I am trying to alter select list option of a content type using hook_form_alter.

I am setting the values to select values and is getting assigned.

Only issue is that its getting logged out with single refresh to create form of that content type form or try to submit that form. What am i doing wrong in the code.

Thanks in advance.

function hook_form_alter(&$form, &$form_state, $form_id)
{
    if($form_id == 'product_node_form')
    {

            $users = db_select('users', 'u');
            $users->join('users_roles','ur','u.uid = ur.uid');
            $users->fields('u',array('name'));
            $users->fields('ur',array('uid'));
            $users->condition('ur.rid',6,'=');
            $users->orderBy('u.uid');
            $users = $users->execute()->fetchAll();

            $vendor_list = array("Tan" => "Tan");

            foreach($users as $key => $user)
            {
                $vendor_list[$user->name] = $user->name;
            }
            $form['field_publish_to']['und']['#options'] = $vendor_list;
    }
}

Try to rename the variable $user/ $users. May be your code is overwriting the default $user object of drupal. Try after renaming the variables $user/ $users.


why can't I create comment using rules? Simple rule:

after update node: create new entity with type: "comment"

but after update node, nothing happens...

why that?

UPD, added screenshots of my rule:

UPD2: i can create node by creating entity, but not a comment o_O

UPD3: ok understand what is the problem: i called the content type(machine name) 'task' =)

UPD4: errors while updating node and creating comment:

full error message: "Unable to get variable entity_created, it is not defined."

Because you did not save it.

Add action of Save Entity.


Drush not working after restart I had Drush working yesterday and was able to use it to download a copy of Drupal. After shutting down my machine last night it now won't work.

which drush does nothing today. drush help gives: -bash: drush: command not found

I guess that when I installed it yesterday, some setting was live in the terminal allowing it to work, but this wasn't saved or stored so after restarting it doesn't work. On the day drupal was installed I closed and reopened the terminal window several times and Drush kept working.

I can still see my copy of 6.5.0 in $Trotter/.composer/vendor/drush/drush/

The installation instructions say:

  Now add Drush to your system path by placing export PATH="$HOME/.composer/vendor/bin:$PATH" into your ~/.bash_profile (Mac OS users)

I followed these instructions on creating a bash profile and have saved my bash profile with the single line in it:
export PATH="$Trotter/.composer/vendor/bin:$PATH"

Following the instruction below in terminal didn't do anything for me:

  Type ". .bash_profile" to reload .bash_profile and update any functions you add

Please suggest what I need to do to get Drush working again, and keep working after restarting the machine.

Here is the location of composer inside my home directory:

The use of $username in the path looks a bit suspect. You should use .bash_profile for mac as as .bashrc seems not to be auto loaded.
There usually isn't a /username/ directory, its usually /home/username/ so your path should probably be:

export PATH="$HOME/.composer/vendor/bin:$PATH"

then execute this to load the file:

source .bash_profile

or open a new terminal


Can't login using OpenId (core) and Google profile I'm using the OpenId module (included in core v7) but can't link an OpenId to an existing account. Every time I try to add it an error occurs:

  Sorry, that is not a valid OpenID. Ensure you have spelled your ID
  correctly.

I'm trying to connect using a Google profile. The URL I'm trying is "https://profiles.google.com/x" (x => my id).

Has anybody succeeded in doing this?

The following works for me in Drupal 7:

https://www.google.com/accounts/o8/id

For more information, see Whats My Google OpenID URL?.


How to get all rows from a database table? I have the table where I store uid column. I want to get all the values from that table, but I only get the frist element.

My query:

$sql = db_select('voting_nomination_counter', 'v')
->fields('v', array('uid'))
->execute()
->fetchAssoc();

Where is my problem?

DatabaseStatementBase::fetchAssoc fetches the next row and returns it as an associative array.

$query = db_select('voting_nomination_counter', 'v');
$query->fields('v',array('uid'));
$result = $query->execute();
while($record = $result->fetchAssoc()) {
  print_r($record);
}


How to remove undesired local task tabs I have a node type 'faq'. For node type 'faq' I need to remove the tab 'node clone'.

For that I have done the following codes.
In node_clone.routing.yml I have the following code

node_clone.prepopulate_node:
  path: '/node/{node}/clone/prepopulate'
  defaults:
    _title: 'Clone content'
    _controller: 'node_clone.form_controller:getContentResult'
  requirements:
    _custom_access: 'node_clone.form_controller:access'
    #_node_add_access: 'node:{node_type}'
    node: '\d+'
  options:
    _node_operation_route: TRUE
    parameters:
      node:
        type: 'entity:node'

In my controller file

public function access(AccountInterface $account, NodeInterface $node) {

      $node_type = ($node->getType());
      if($node_type=="faq")
      {
          $access = new AccessResultForbidden();

      }

    if ($account->hasPermission('clone node') || ($node->uid->value === $account->id() && $account->hasPermission('clone own nodes'))) {
      $access = new AccessResultAllowed();
    }

    else {
      $access = new AccessResultForbidden();
    }
    $access->addCacheableDependency($node);
    $access->cachePerPermissions();
    if ($access->isAllowed()) {
      $access = $access->andIf($node->access('view', $account, TRUE));
    }
    if ($access->isAllowed()) {
      $node_type = NodeType::load($node->getType());
      $access = $access->andIf($this->nodeAddAccessCheck->access($account, $node_type));
    }
    return $access;
  }

Please help me to find out what's wrong with my code? Is this enough or I should do something else?

To completely remove the tab from all pages you can use hook_local_tasks_alter().

function mymodule_local_tasks_alter(&$local_tasks) {
  unset($local_tasks['local_task_to_remove']);
}

Where local_task_to_remove is the tab you want to remove.

To have it removed from some pages you could use hook_menu_local_tasks_alter() instead. Something like:

function mymodule_menu_local_tasks_alter(&$data, $route_name) {
  $routes = ['entity.entity_view_display.node.default', ...]; // put other routes in place of '...'
  if (in_array($route_name, $routes)) {
    unset($data['tabs'][0]['local_task_to_remove']);
  }
}


Add menu item in hook form submit I have an entity, when i submit this entity i want to add the new entity created in a menu as a link. But in this menu i have a tree links so i don't know how to put my link in a specific tree. I saw the "mlid" and the "plid", i think "mlid" is the id of the menu and the "plid" is the id of the mother link.

So if I want to add a new item, what do I need to do? Do I get the ID of the parent link?
Do I need to use menu_link_save()? How do I construct my new link?

This is the code I am using.

$menu_intervenant_loaded = menu_load_links('menu-intervenant-project'. $idProject);

foreach ($menu_intervenant_loaded as $menu_item) {
  $menutitle = str_replace(" ","+", $menu_item['link_title']);
  $mlid = $menu_item['mlid'];
  $link = menu_link_load($mlid);
  $haschildren = $menu_item['has_children'];
  if ($menutitle == "Entreprises") {
    //The parent link: here is where I need to create my link.
    $item = array(
        'title' => 'Montitre',
        'access' => TRUE,
        'link_path' => 'encore un test',
        'link_title' => 'Mon titre qui fonctionne pas',
        'plid' => $mlid,
        'customized' => 1,
        'external' => 1,
    );

    menu_link_save($item);
  }
}

EDIT : With this code the link appear when i debug my menu before submit, but doesn't appear in my administration and front-end where the menu is placed..

Value of plid is the menu link id of the item you want your new item to be a child of (=parent id).

To create your link, simply use something like:

$item = array(
  'link_path' => 'node/' . $node->nid,
  'link_title' => $node->title,
  'plid' => 426,
);
menu_link_save($item);


Writing PHP into views field template twig I'm less familiar with D8, but I need to re-write a views field output using some PHP. I've made a custom field template HTML.twig file, but I'm not sure what I need to do to be able to run a PHP execution on my field to render it out as I want.
edit:
I am trying to run a function on the User ID as I have a module which hashes it before sending it to an external platform, however, now the client wants the understand which user is which, and the only way I can think to do this is by performing the same hashing code on the User ID in a format I can easily cross reference the user with their hashed output
I have a very basic view table showing only the User ID and email address, and I've managed to create a views field override using this page which has overwritten my field successfully. But now I want to run a command I'm going to copy from my contrib module, the below to be specific, so that I can work out which User ID relates to which hashed code
return Crypt::hmacBase64($uid, \Drupal::service('private_key')->get() . Settings::getHashSalt());

You can write Twig directly into your view with a Custom text field.

Using Twig as an entry point, you can use all of the Twig functionality and filters that ship with Drupal, as well as expanding on these with modules like Twig Tweak and Twig Field Value. You can also write your own Twig extensions, which are written in PHP. Here are two suitable tutorials:

https://opensenselabs.com/blog/tech/twig-extension-drupal
https://medium.com/@yuseferi/how-to-write-custom-twig-filter-in-drupal-8-1c2981dbf1e3


How to display $variables in drupal 6 preprocess function? I'm having difficulty trying to figure out what variables are within the scope of my hook_preprocess function.  I even tried to print_r($variables['fields']), but I keep getting this long recursive mess.  Is there a much easier way in drupal 6 to see what values I can use?

Install the Devel module.

Once installed use the function dpm() like this: dpm($variables);

This will give you a nice print out of your variables.


views ajax form alter I have some slightly complicated ajax form logic that I'm struggling with.

I would like to replicate the following form conditions.

radio1 - always visible
option1
option2
option3

radio2 - only visible if option 2 and 3 are selected in radio1
option1
option2
option3

select3 - only visible if option 1 is selected in radio1
contents of select list to be controlled by on options in radio2

Problems

when radio2 is changed it still fires the ajax function

when the form is submitted the select list uses the default option set rather than one that has been built from the selection radio2

Below is the code I have used following the ajax example from the examples module.

function uk_general_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
if($form['#id'] == 'views-exposed-form-documentation-search-page') {
if(!empty($form_state['values'])) {
  $form_state['input'] = array_merge($form_state['input'], $form_state['values']);
}
$doc_type_options = $form['type']['#options'];
$form['type'] = array(
  '#type' => 'radios',
  '#options' => $doc_type_options,
  '#title' => '',
);

$doc_line_options = $form['line']['#options'];
$line_selected = isset($form_state['values']['line']) ? $form_state['values']['line'] : key($doc_line_options);
$form['line'] = array(
  '#type' => 'radios',
  '#options' => $doc_line_options,
  '#title' => '',
  '#ajax' => array(
    'callback' => 'uk_general_forms_documents_products',
    'wrapper' => 'products-dropdown-replace',
  ),
  '#states' => array(
    'visible' => array(
      ':input[name="type"]' => array(
        array('value' => '29'),
        array('value' => '31'),
        ),
      ),
    'disabled' => array(
      ':input[name="type"]' => array('value' => '30'),
      ),
    ),
  );
$form['title'] = array(
  '#type' => 'select',
  '#prefix' => '
',
  '#suffix' => '
',
  '#options' => _get_products($line_selected),
  '#states' => array(
    'visible' => array(
      ':input[name="type"]' => array('value' => '29'),
    ),
    'disabled' => array(
      ':input[name="type"]' => array(
        array('value' => '30'),
        array('value' => '31'),
      ),
    ),
  ),
);
}
}

function uk_general_forms_documents_products($form, $form_state){
  return $form['title'];
}

function _get_products($selected) {
  $product_query = new EntityFieldQuery;
  $product_query->entityCondition('entity_type', 'node')->entityCondition('bundle', 'product')->fieldCondition('field_line', 'tid', $selected)->propertyOrderBy('title', 'ASC');
  $result = $product_query->execute();
  $product_nids = array_keys($result['node']);
  $products = entity_load('node', $product_nids);
  $titles['All'] = '- Any -';
  foreach($products as $product) {
    $titles[$product->title] = $product->title;
  }
 return $titles;
}

i finally worked this one out, I strppied the form right back and removed all the states and got the ajax call working first. This was a bit of a hack as I had to access the $_GET variable directly and using the following line I was able to check whether or not the page had already been searched.

if(isset($_GET['line_2'])) {
  $line_2_selected = $_GET['line_2'];
}
else{
$line_2_selected = isset($form_state['values']['line_2']) ? $form_state['values']['line_2'] : key($doc_line2_options);
}

After this the problem was either having the ajax selectively removed ot depending on the values in the parent checkboxes. What I actually did was add the same list twice and then disable one or the other depending on the value in the first checkbox. Doing this greatly reduced the complexity of the states array.

$form['line'] = array(
  '#type' => 'radios',
  '#options' => $doc_line_options,
  '#default_value' => $line_selected,
  '#title' => '',
  '#prefix' => '
',
  '#suffix' => '
',
  '#states' => array(
    'enabled' => array(
      ':input[name="type"]' => array('value' => 31)
    ),
    'visible' => array(
      ':input[name="type"]' => array('value' => 31)
      ),
  ),
);

$form['line_2'] = array(
  '#type' => 'radios',
  '#options' => $doc_line2_options,
  '#default_value' => $line_2_selected,
  '#title' => '',
  '#prefix' => '
',
  '#suffix' => '
',
  '#ajax' => array(
    'callback' => 'uk_general_forms_documents_products',
    'wrapper' => 'products-dropdown-replace',
    ),
  '#states' => array(
    'enabled' => array(
      ':input[name="type"]' => array('value' => 29)
      ),
    'visible' => array(
      ':input[name="type"]' => array('value' => 29)
      ),
    )
  );

The previous ajax functions all worked as expected.