How to update custom user field on form submit I want to create a basic page that has only one of my custom user account fields listed, and available to edit.

For example, I have a custom user account field: field_companyname

Rather then directing the user to go to www.example.com/?q=user/1/edit,
I want the user to go to a different page (i.e www.example.com/node/5).
On this page, there should only be a single text input field, and a submit button to save the new data to the user account.

I'm pretty sure I need to implement user_save(), but I just don't know where to go from here.

// load user object
$existingUser = user_load('USERID');

// update some user property
$existingUser->some_property = 'foo';

// save existing user
user_save((object) array('uid' => $existingUser->uid), (array) $existingUser);

Any help or pointers would be much appreciated. Thanks for looking!

EDIT: I was able to load the entire user account edit form onto a node using the following code:

<?php
  module_load_include('pages.inc', 'user', 'user');
  global $user;
  $account = user_load($user->uid);
  $output = drupal_render(drupal_get_form('user_profile_form', $account));
  return $output;
?>

However, I still cannot figure out how to display ONLY my single custom field. Any help is greatly appreciated.

EDIT #2: I used CSS to hide the other fields that I did not want to display. Seems like there should be a better way to do this. But I guess this will work for now, unless anyone else can chime in :-)

Thanks again for looking.

Use field_attach_form in your page with the field name and user object. You can use field_attach_form_validate and field_attach_submit
to validate and submit the values.


Views 3: how to list users related to nodes category and exposed filter by that category I need to list the node authors based on node category and also expose filter with that category. Can any one tell me how to solve this issue?

Follow below steps to solve the issue.

Add relationship node author.
In View Fields add field Node Author Name
Add filter Node Category Field that is used to Categorize content.
Expose the above filter
Select Group By Node Author Name in View Style Settings so that you can see DISTINCT users belongs to Node Category

That should work i hope !


How do I send data to a template page on form submission? I am building a weather API in Drupal 7, and I am unable to send weather report to my custom template file. Everything is working fine but the result is not displayed; everything is working as expected except result display.

.info

name = BM Weather API Part 2
description = Display the current weather condition of a specific location
package = BM API
version = VERSION
core = 7.x

.module

<?php
function BM_weather_API_part2_theme() {
  return array(
    'BM_weather_API_part2' => array(
      'template' => 'BM_weather_API_part2',
      'variables' => array('msg' => NULL),
    ),
  );
}

function BM_weather_API_part2_menu() {
  $items['BM_weather_API_part2'] = array(
    'title' => 'Weather API - Part 2',
    'page callback' => 'BM_weather_API_part2_view',
    'access arguments' => array('access content'),
    'file' => 'BM_weather_API_part2.pages.inc',
  );

  return $items;
}

.inc

function BM_weather_API_part2_view() {
  $dis = drupal_get_form('BM_weather_API_part2_form');
  return $dis;
}

function BM_weather_API_part2_form() {
  $form['location_name'] = array(
    '#title' => 'Location',
    '#type' => 'textfield',
    '#description' => 'Enter Location Here.',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Get Weather Report',
    '#submit' => array('BM_weather_API_part2_get_weather_report'),
  );

  return $form;
}

function BM_weather_API_part2_get_weather_report($form, &$form_state) {
  $loc_name = $form_state['values']['location_name'];

  if (ctype_digit($loc_name)) {
    form_set_error('BM_weather_API_part2_character_required', t('Please Enter Proper Location Name.'));
    return;
  }
  elseif ($loc_name == '') {
    form_set_error('BM_weather_API_part2_character_required', t('Please Enter Location Name'));
    return;
  }

  $freport =  get_weather_from_google($loc_name);

  return theme('BM_weather_API_part2', array('msg' => $freport));
}

function get_weather_from_google($loc) {
  // $finalreport contains the final report coming from google
  return  $finalreport;
}

.tpl

print $msg;

Form submission handlers (in your case, BM_weather_API_part2_get_weather_report()) don't return any value. See user_login_submit(), and user_register_submit() as examples of form submission handlers.

What I would suggest for your form submission handler is the following:

Set $form_state['rebuild'] to TRUE, and $form_state['BM_weather_API']['weather_result'] to the value obtained from the weather service; this would cause the form builder to be called again.
At this point, the form builder should verify if the content of
$form_state['BM_weather_API']['weather_result'] is not empty, and show the output obtained from the weather service, for example using code similar to the following one.

// First case.
$form['result'] = array(
  '#theme' => 'BM_weather_API_part2',
  '#msg' => $form_state['BM_weather_API_part2']['weather_result'],
);

// Second case.
$form['result'] = array(
  '#markup' => $form_state['BM_weather_API_part2']['weather_result'],
);

In the first case, $form_state['BM_weather_API_part2']['weather_result'] is the value obtained from the weather service, which needs to be passed to the theme function; the code would cause the theme function to be called, and get the value of $form_state['mymodule']['weather_result] as value for the $msg variable used in the template file. In the second case, $form_state['BM_weather_API_part2']['weather_result'] is the value obtained from the theme function, which got the weather service's result.

The code I would write is similar to the following one.

.module

<?php
function BM_weather_API_part2_theme() {
  return array(
    'BM_weather_API_part2' => array(
      'template' => 'BM_weather_API_part2',
      'variables' => array('msg' => NULL),
    ),
  );
}

function BM_weather_API_part2_menu() {
  $items['weather/report'] = array(
    'title' => 'Weather API - Part 2',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('BM_weather_API_part2_form'),
    'access arguments' => array('access content'),
    'file' => 'BM_weather_API_part2.pages.inc',
  );

  return $items;
}

.inc

function BM_weather_API_part2_form() {
  $form['location_name'] = array(
    '#title' => 'Location',
    '#type' => 'textfield',
    '#required' => TRUE,
  );

  if (!empty($form_state['BM_weather_API_part2']['weather_result'])) {
    $form['result'] = array(
      '#markup' => $form_state['BM_weather_API_part2']['weather_result'],
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Get the weather report',
    '#validate' => array('BM_weather_API_part2_form_validate'),
    '#submit' => array('BM_weather_API_part2_form_submit'),
  );

  return $form;
}

function BM_weather_API_part2_form_validate($form, &$form_state) {
  if (BM_weather_API_part2_check_location($form_state['values']['location_name'])) {
    $form_state['BM_weather_API_part2']['weather_result'] = FALSE;
    form_set_error('location_name', t('Please enter a proper location name.'));
  }
}

function BM_weather_API_part2_form_submit($form, &$form_state) {
  $form_state['BM_weather_API_part2']['weather_result'] = theme('BM_weather_API_part2', array(
    'msg' => BM_weather_API_part2_get_weather($form_state['values']['location_name']))
  );

  $form_state['rebuild'] = TRUE;
}

function BM_weather_API_part2_get_weather($loc) {
  // ...
}

I will add some notes about your code.

In the implementation of hook_menu(), the array keys are the paths associated with the menu callbacks; in your case, as you use $items['BM_weather_API_part2'], the URL for that menu callback would be http://example.com/BM_weather_API_part2 (replace example.com with the URL of your site). It is preferable a path like weather, or weather/report, which is similar to the paths used from Drupal, such as node/1, user/1/edit.
When defining a menu callback, you can use 'page callback' => 'drupal_get_form' and pass as first argument of "page arguments" the name of the form builder; there isn't the need to define a function such as BM_weather_API_part2_view(), whose only purpose is to call drupal_get_form().
The form submission handlers don't check if the submitted values are correct; that is a task for the form validation handlers. That is why I am using a form validation handler, in my example code.
If the users need to enter a value for a form field, then you can simply use '#required' => TRUE for that form field, as I did.
ctype_digit() returns TRUE when the parameter it gets is a string containing only digits. I am not sure that is what the user should input in your case, as a number is not what I would consider a location name. If the user really needs to enter a number, the description for the "Location" form field should say that, and it should also explain what type of input the form it is expecting (e.g. a zip code).
The first argument of form_set_error() is the form field ID. As you don't have any form field that uses "BM_weather_API_part2_character_required" as ID, form_set_error('BM_weather_API_part2_character_required', t('Please Enter Proper Location Name.')) is not highlighting any form field, which is part of the purpose of form_set_error(). In your case, you should use form_set_error('location_name', t('Error string')), as location_name is the form field ID for the field you are reporting an error.
All functions implemented in a module should be prefixed with the short name of the module (after an underscore, if the function is "private"); in this way, there isn't any collision between different modules, which is what happens if two different modules would define a get_weather_from_google() function.
If the template file just prints the value it gets between its variables, then there isn't the need of a template file, or a theme function; you just use code similar to the following one:

function BM_weather_API_part2_form_submit($form, &$form_state) {
  $form_state['BM_weather_API_part2']['weather_result'] = BM_weather_API_part2_get_weather($form_state['values']['location_name']));
  $form_state['rebuild'] = TRUE;
}

I wrote the example code assuming that your template file does more than just printing a variable it gets, and you didn't show all the code for the template file; if the template file does only that, then the template file, and the theme function are not necessary.

As side note, if the short name of your module contains uppercase characters, you will have problems with hook_update_N() being executed. You should always use lower case characters in the short name of your module.


Drush Not recognizing it's in a drupal root Drush commands seem to succeed but don't.

For example, drush dl module results in:

  Install location /doc_root/feeds_tamper already exists. Do you want to overwrite it? (y/n): y
  Project feeds_tamper (7.x-1.0-beta5) downloaded to /doc_root/feeds_tamper.
  Project feeds_tamper contains 2 modules: feeds_tamper_ui, feeds_tamper.

However, it's the wrong download location, and there is no feeds tamper in that location.

Drush status returns:

  PHP configuration: C:\xampp\php\php.ini
  Drush version: 5.9

I am in the document root of the Drupal site.

This is on Windows with Cygwin.

If your settings.php file is inside a directory named default, then Drush will find it whenever your current working directory is anywhere inside the document root.  However, if settings.php is in some other directory, then you must either cd to the directory that contains settings.php, or identify your site via some other technique -- for example, by specifying --uri=mysite.com, or by using a Drush site alias.


Style Views without preprocess I created basic custom - made layout in Drupal 7 by setting up ( layout.info html.tpl.php page.tpl.php style.css )

I have also created Views in order to filter some certain content (text and photo). Is there a way to theme the Views but without preprocess functions. So no coding in the template.php ? How to do that if it is possible?

Well you could always assign custom CSS classes to each field and target them for styling. Template.php file should be used more for a data manipulation purpose anyway, rather than styling.


How can I change the way list appears when I click a tag? When I select a tag link, result shows the title and content. How can I change the list of related article appears only with title and not include any content please?

There are a few ways to achieve that.

First and the easiest way is to go to the display settings of the content type and hide all fields in teaser view mode.

Second way is to use Views module, which ships with a taxonomy term view. You need to go to the views administration, structure/views, and enable this view. Or better, clone this view and enable the cloned one. This way you have more options then only to show the titles. However, it can be an overkill if you only need to show titles.


How to add subquery in views to remove particular type of rows? I have applied join to users table with node_revision table like below:
function custom_overrides_views_data_alter(&$data) {

  $data['users']['node_revision'] = array(
    'title' => t('Users revisions authored'),
    'help' => t('Relate a user to their revisions'),
    'relationship' => array(
      'base' => 'node_revision',
      'base field' => 'uid',
      'relationship field' => 'uid',
      'handler' => 'views_handler_relationship',
      'label' => t('revisions bubbla'),
    ),
  );
}

And by creating view now I got number of revisions per user like below:

Westerberg (15752)
Eriksson (4305)
Jakob (4182)
Andersson (4153)

But now I want to remove those revisions which are created when user created node first time ie: will only show edits but not the revisions which are created first time when new node was created. To solve this logic is to remove nodes having below true:
excluding the “first time created” nodes (original node revision)
node.created = node_revision.timestamp

I tried using query alter but it uses quotes around field please suggest how to remove that ?
if ($view->name == "my_view") {

    $sub_query = db_select('node', 'n')
      ->fields('n', array('created'))
      ->condition('n.created', 'node_revision_users.timestamp');

    $view->query->where[1]['conditions'][] = array(
      'field' => 'node_revision_users.timestamp',
      'value' => $sub_query,
      'operator' => 'NOT IN'
    );

  }

Output problem is like screenshot:

Please suggest! thanks

You should use where() to match table columns instead of condition

if ($view->name == "my_view") {
    $sub_query = db_select('node', 'n')
      ->fields('n', array('created'))
      ->where("n.created = node_revision_users.timestamp");

      $view->query->where[1]['conditions'][] = array(
        'field' => 'node_revision_users.timestamp',
        'value' => $sub_query,
        'operator' => 'NOT IN'
      );
}

Update

Why where() not condition()

Syntax for condition:

$query->condition($field, $value = NULL, $operator = '=')

shows condition() is for building standard condition fragement

Syntax for where:

$query->where($snippet, $args = array())

shows where() is for building any arbitrary SQL as conditional fragment.

$snippet may contain any legal SQL fragment.


Hide the option of Payment method "No Payment Required" based on user role I used module "No payment required" for giving extra payment method as per my client requirement.

I created a site with two user roles: 1. Merchant, 2. Customer.

Option "No payment required" should only display to users with "Customer" role, which is given permission by Merchant. I have searched in google but there is no luck.

In Drupal Commerce each payment method is essentially a rule. So just like with any rule, you'll need to add your required condition to that payment method rule.

Find Payment Method Configuration page - admin/commerce/config/payment-methods.

You'll see payment method "No Payment Required (Payment)" in the list of "Enabled payment method rules" (if it is enabled). If not enabled - enable that payment method.

Then click Edit next to that rule, and add condition "User has roles". Select the role "Customer", save, test and you're done.


Attaching a view page display to a tab in a content type? I've built a CSV exporter by heavily modifying a template file from Views Bonus Pack's CSV feed Views plugin that formats all the content in a particular view exactly how I want it.

Now, I just need to find some way of integrating it into the work flow. Ideally, on each "projectsheet" content-type node, there would be 3 tabs for admins: View, Edit, Export.

The exporter feed is attached to a Page display that's part of the view. If I set that page's path to something like "node/%/export", it usurps the default display of that node and the node becomes that view.

How do I create a new tab, to which a Views Page display is attached, that's visible only in a certain content type and doesn't take over the default view of that content type?

I'm using Drupal 6 and the Views UI; considering everything I've done is in Views UI as a template for Views Bonus Pack, I'd really like to not code a new module to achieve this (i.e., just use Views UI to accomplish it if possible).

Thanks!

In the Page settings section of the Page display of your view:

Path: node/%/export
Menu: Menu tab, Title: Export

You'll probably have an argument in your view already. In that argument's configuration:

Validator: Node
Node type: projectsheet (or whatever node types to display tab for)


developing a site in drupal made a mess in modules .. is there better way? When I develop a site in Drupal, I test a couple of modules to see what best suits my needs. The problem is that, if it is a large site, I find myself with a lot of modules and patches (disabled / uninstalled), which still exist in the modules folder. There are a lot of modules that don't have an uninstall feature; the result is that I get many unused tables in the database, and many used files to delete.

Is there a better solution, or way to proceed for testing modules?

You can of course create a test site to experiment with certain modules and patches before adding them to the real site.

Version control is also really helpful, because it allows you to revert to a previous version of your code. However you need to keep in mind that your database is not under version control, so you need to take a snapshot of that as well to do a proper rollback.

A more advanced solution is to use drush make and the features module. The features module allows you to store a lot of configuration in code. When combined with drush make, it allows you to roll out a fresh copy of your code again and again.


How to get entity id of newly created entity using entity_get_controller I am crating the new entity in drupal a below,

$entity = new stdClass();
$entity->type = 'entity_type';
$entity->id = 0;
$entity->title = 'Entity Title';

//Add data to fields
$entity->field_introduction = array
            (
                'und' => array
                (
                    "0" => array
                    (
                        'value' => $strIntroduction
                    )
                )
            );

     .
     .
     .
     .

    //After adding all the fields, I am saving entity as follows,

entity_get_controller('summary_report')->save($entity);

Entity get saved successfully. After this I want entity id for the further manipulations.
How I get this newly created entity id.

Assuming id is the name of your ID entity key, use this after the save:

$id = $entity->id;

You also have the option of using entity_extract_keys if you want to do it more generically:

list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);


How can I remove unwanted CSS found in the parent theme? I'm working on a sub-theme of Bootstrap Barrio, which includes a table.css stylesheet. I don't want this stylesheet from the parent theme to be included in my sub-theme.

How do I eliminate a CSS file from sub-theme's parent?

You can override it by adding a blank file with the same name in your theme (or you can add your own contents). Or, you can remove it altogether with libraries exclude: https://www.drupal.org/docs/theming-drupal/adding-stylesheets-css-and-javascript-js-to-a-drupal-theme#override-extend


No orders in user profile with custom state of order-status Drupal 6 + Ubercart. I had created some new order statuses with own state. But when order gets this status, order dissapears from user "Ordered products" (in user's profile)

How to fix this?

The Order History page (user/%user/orders) retrieves orders that are general in scope.

If you created a custom Status through /admin/store/settings/orders/edit/workflow/create, this scope excludes Canceled & In Checkout statuses. If you've created a custom state through hook_uc_order_state(), you need to the scope to general for it show up.


Get a list of revision IDs for any given entity? What's the most uniform method for getting a list of revision IDs for any given entity, programmatically?

Figured it out. I'll leave it here because it might be useful to someone down the road.

You can use this function to get a list of all revisions ids for any given entity.

/**
 * Get a revision id list for a particular entity.
 */
function get_entity_revision_list($type, $entity) {
  $info = entity_get_info($type);
  if (!isset($info['revision table'])) {
    // If this entity does not track revisions then return FALSE.
    return FALSE;
  }
  if (!isset($info['entity keys']['revision'])) {
    // If for whatever reason a revision table was defined, but no revision key
    // then also return FALSE.
    return FALSE;
  }
  $revisions = db_select($info['revision table'], 'r')
    ->fields('r', array($info['entity keys']['revision']))
    ->condition($info['entity keys']['id'], $entity->{$info['entity keys']['id']})
    ->execute()
    ->fetchAllAssoc($info['entity keys']['revision']);
  return array_keys($revisions);
}


How to disable picture button after click? I'm new at Drupal CMS and programming at all, but I'm trying to find my way to solve this problem.Unfortunately unsuccesful for now.
I've installed Drupal 7.5 and Multipurpose theme which has social icons to redirect to facebook,twitter and etc.In theme settings there is an option to paste link with profile.I wanted to tweak their function a bit but I'm stuck with the code int the page.tpl.php file.
What I'm trying to do is basicly to check if the user is logged in, and if he is and a link was given in the setting of the theme to redirect to the social profile.The problem occurs when the user presses the button twice or more because the link copies over and over instead of refresh...for example: 1 click: https://www.facebook.com/user and on the 2 click becomes: https://www.facebook.com/user/user and so on.
The code:

 <?php if (!$logged_in) : ?>
      <?php if ($twitter_url): ?>

        <a title="<?php print $site_name; ?> in Twitter" href="<?php print $twitter_url; ?>"><img alt="Twitter" src="<?php print base_path() . drupal_get_path('theme', 'multipurpose') . '/images/social/twitter.png'; ?>">  <?php endif; ?>

<?php endif; ?>

So the question is how can I disable the button(become inactive not hidden) after one click or is there any other approach to solve this problem?
Thank you!

The link needs a slash in front of it:

/user/login

instead of:

user/login

Logout would be:

/user/logout

You need to use relative paths or you will continue encountering this behavior. A better way would be to send the variables to your template(s) via the appropriate preprocess function, and use the l() function to create links.


module error in drush My task is to update all modules of  a site and commit. Everything goes well except when I ran the command drush pm-update projects drupal-6.28

  PHP Fatal error:  Call-time pass-by-reference has been removed in /Users/scottnassery/c2d-deals2/sites/all/modules/contrib/uc_post_affiliate_pro/uc_post_affiliate_pro.module on line 926
  Drush command terminated abnormally due to an unrecoverable error.   [error]
  Error: Call-time pass-by-reference has been removed in
  /Users/scottnassery/c2d-deals2/sites/all/modules/contrib/uc_post_affiliate_pro/uc_post_affiliate_pro.module,
  line 926

  Fatal error: Call-time pass-by-reference has been removed in /Users/scottnassery/c2d-deals2/sites/all/modules/contrib/uc_post_affiliate_pro/uc_post_affiliate_pro.module on line 926
  Scotts-MacBook-Pro-2:c2d-deals2 scottnassery$ drush up uc_post_affiliate_pro --security-only --no-core
  PHP Fatal error:  Call-time pass-by-reference has been removed in /Users/scottnassery/c2d-deals2/sites/all/modules/contrib/uc_post_affiliate_pro/uc_post_affiliate_pro.module on line 926
  Drush command terminated abnormally due to an unrecoverable error.   [error]
  Error: Call-time pass-by-reference has been removed in
  /Users/scottnassery/c2d-deals2/sites/all/modules/contrib/uc_post_affiliate_pro/uc_post_affiliate_pro.module,

My question is how can I fix that error and how can I restore the module to a old version should I redownload it  and replace it?

Recently, Drush changed the default setting for recoverable errors to abort rather than continue when they are discovered. If this is causing problems, e.g. in an old module, then you can turn it off.

Create a file called drushrc.php, and place it in $HOME/.drush. Add the following contents:

<?php
$options['halt-on-error'] = FALSE;

You should then be able to continue without needing to fix the error in the non-compliant module.


Live filtering of nodes by taxonomy terms? As part of a company website redesign, the designer I've partnered up with has come up with an interesting way of displaying projects and people using taxonomy. We're just trying to figure out how to implement it in Drupal 7:

We have project, and people, and a vocabulary describing specific skills and topics that are common to both.  Each project and person has an associated node containing the relevant terms.

What we would like to have is a master display for each type: people and projects.  Each master display will show all the terms in the vocabulary (this vocabulary will be kept very small), and all projects/people.  However, when a user clicks on one of the terms, the display of relevant nodes will be filtered to show only the nodes containing that term.

We already have the code to handle the live filtering - if these were static HTML pages it would be simple.  But considering that we are using Drupal for the site, it seems rather silly not to take advantage of having a database to query.

I've spent the last few hours scouring the web for anything that will let me accomplish this.  Ideally I need something that will identify/expose the terms associated with the nodes...  It seems Views is the likely answer, but I can't seem to place both the terms and the content type lists in the same view.  This page from a related question here seems to come close, but I am not currently using Panels and I'm still new enough to Drupal that I have no idea how to use the hook referenced.

Hopefully I've explained this clearly enough, but let me know if I haven't. Thanks in advance!

What you're after is known as Faceted Search. You're able to drill down your Views results based on taxonomy terms (or other fields for that matter) as you described.

A good example of Faceted Search can be found within the Commerce Kickstart demo store.

You'll need the Search API module as a basis, and I found a really good tutorial on getting started with Faceted search here: http://vimeo.com/15556855

If you're setting up a site which will get a lot of traffic, you might want to consider using Apache Solr to take some stress off your database when performing search queries.


How not show in a View certain taxonomy items if there are no associated nodes? I'm using a View to display all the items from a taxonomy term list I've setup. The taxonomy term is used as a field in my nodes. That's all fine.

Now, I created another view called 'all categories' that displays all the taxonomy terms (each term is only displayed once). When a user clicks the term they automatically go to the term page and see the nodes that are using that term.

The problem is that some of the terms haven't yet been used by any nodes so when the user clicks the term name for those it just takes them to a page that says [name] at the top with no other information. I'd rather just hide any categories that have no associated nodes, but I don't know how to do it. I'd also be open to other suggestions for alleviating this issue.

Note: if a term DOES have nodes associated with it and you click the term it takes you to a page with the term as the title and the associated nodes listed below the title.

Here's the settings I have for the 'All categories' view:

Show: Fields
Fields: Taxonomy term: Name (link this field to its taxonomy term page)
Filter Criteria: Taxonomy vocabulary: Machine name (=Category)

Easiest way is to add a relationship in the view to the node type that contains the taxonomy term reference field and make it mandatory. This will force Views to only return the taxonomy terms that are present on a node.

Edit your view
Expand "advanced" (if its not already expanded)
Click "Add" beside Relationships
Click "Taxonomy term: Representative node"
Click "Require this relationship"
Click "Apply"

Note: I used the representative node vs the content with term option for performance reasons, the former only retrieves a single node for each term vs matching every term to every node


Comment Author details are not displayed when comment is submitted by REST API Currently I am using the following Drupal 8 REST method

POST: http://example.com/entity/comment

Content-type: application/json

    {
      "entity_id":[{"target_id":123}],
      "entity_type":[{"value":"node"}],
      "comment_type":[{"target_id":"comment"}],
      "field_name":[{"value":"comment"}],
      "subject":[{"value":"Goodbye World"}],
      "comment_body":[
        {"value":"
See you later!
","format":"basic_html"}
      ]
    }

201 - Created

This I referred from this link https://goo.gl/kXCS8Q
The comment is getting created properly but the Comment's Author Details are not been displayed.

Can anyone tell what else I need to send the parameters for Comments?

Just adding the solution here.

To get or determine a specific REST parameters, add these fields in your view or content manage fields, then try to access it by running the GET method command. It will show up all parameters of the content/node you need.

Then you can use POST method when planning to update or creating node of your need.


How to alter the "Request new password" form validation I have adapted the login procedure with hook_form_FORM_ID_alter so that another database is also checked for credentials. Now I need to change the forgot password validation as well. It seems the FORM_ID of this form is user_pass, however, the hooks I define for that do not trigger. I also tried with hook_form_alter to see what form was triggered, but that hook also never fires (while it does for login for example).

Is the "Request new password" some kind of special form? Is it possible to change the validation handler of this form?

I'm using Drupal 7.

Nothing special about this form, you can alter it just like any other:

function MYMODULE_form_user_pass_alter(&$form, &$form_state) {
  $form['#validate'][] = 'MYMODULE_user_pass_validate';
}

function MYMODULE_user_pass_validate(&$form, &$form_state) {
  // Your code here
}

Works perfectly fine.


Add the user picture before the username in user listings? I'm trying to add the user picture before the username in user listings. I've copied theme_username into my template.php and I'm trying to call theme with the argument 'user_picture' in order to get the HTML that will render the picture, but the call just returns an empty string. I'm providing the uid as the argument. Where am I going wrong?
Thanks.

function MY-THEME_username($variables) {
  if (isset($variables['link_path'])) {
    // We have a link path, so we should generate a link using l().
    // Additional classes may be added as array elements like
    // $variables['link_options']['attributes']['class'][] = 'myclass';

    // I ADDED THIS LINE

    $output = theme('user_picture', array('account' => $variables['account']));

    // ENDS

    $output .= l($variables['name'] . $variables['extra'], $variables['link_path'], $variables['link_options']);
  }
  else {
    // Modules may have added important attributes so they must be included
    // in the output. Additional classes may be added as array elements like
    // $variables['attributes_array']['class'][] = 'myclass';
    $output = '<span' . drupal_attributes($variables['attributes_array']) . '>' . $variables['name'] . $variables['extra'] . '</span>';
  }
  return $output;
}

theme_user_picture is not a Drupal 7 function, whereas in the example you provide you are using Drupal 7's theme_username function code. Moreover, even in Drupal 6, theme_user_picture returns nothing because in that version of Drupal it's merely a placeholder and the actual themeing of the user entry is handled via the corresponding template file user-picture.tpl.php. This is possibly the reason your theme call returns nothing. Please refer to api.drupal.org to find the correct implementation for your Drupal version.

So, assuming that you are on Drupal 7, note that $variables['account'] is not a fully populated user object and does not contain any reference to the user picture. You need to actually load the user object and give the picture some themeing in order to show it in your listing. Your code could be something like this:

function MY-THEME_username($variables) {
  if (isset($variables['link_path'])) {
    // We have a link path, so we should generate a link using l().
    // Additional classes may be added as array elements like
    // $variables['link_options']['attributes']['class'][] = 'myclass';

    // I ADDED THIS LINE

    //$output = theme('user_picture', array('account' => $variables['account']));
    $user = user_load($variables['account']->uid);
    if (isset($user->picture->uri)) {
      $output = theme('image_style', array('path' => $user->picture->uri,'style_name' => 'thumbnail'));
    }
    // ENDS

    $output .= l($variables['name'] . $variables['extra'], $variables['link_path'], $variables['link_options']);
  }
  else {
    // Modules may have added important attributes so they must be included
    // in the output. Additional classes may be added as array elements like
    // $variables['attributes_array']['class'][] = 'myclass';
    $output = '<span' . drupal_attributes($variables['attributes_array']) . '>' . $variables['name'] . $variables['extra'] . '</span>';
  }
  return $output;
}


What is the right way to implement google_analytics with the eu_cookie_compliance and categories? I'm having difficulty configuring eu_cookie_compliance with multiple categories on a website with Google Analytics tracking. The GA tracking depends on selection of one of the categories.
When the category 'analytics' is enabled, google analytics cookies should be allowed and vice versa.
This comment in a thread for google_analytics shows how to implement the hasAgreed() check within the google_analytics module; in the 'Code Snippet (before)' field:
document.addEventListener('DOMContentLoaded', function(){
    if (!Drupal.eu_cookie_compliance.hasAgreed()) {
        window['ga-disable-UA-0000000-00'] = true;
    }

and in the 'Code Snippet (after)' field:
});

several others in the thread have confirmed that this works for them. In my case however, google analytics is never triggered.
I added the following before the 'if' statement to debug it:
console.log("General: " + Drupal.eu_cookie_compliance.hasAgreed());
console.log("Analytics: " + Drupal.eu_cookie_compliance.hasAgreed('analytics'));

The console shows false for both of the above, no matter what I select, and the google analytics is never triggered.
What could I be doing wrong?

As far as I know, it is not yet possible to activate individual 3rd party services with the EU Cookie compliance module. An update is planned, the concept will be completely revised.
I would recommend using the module "COOKiES Consent Management" https://www.drupal.org/project/cookies, which supports various 3rd party integration modules out-of-the-box, such as https://www.drupal.org/project/google_analytics is supported.


Attach an #ajax callback to a field when the form is reloading from previous ajax request Is it possible to attach an #ajax callback to a field when the form is being regenerated from a previous ajax event (like a submit button)?

What I tried

Adding the #ajax callback to the field when the form is reloading does not seems to trigger anything:

// Adding the ajax event to the field.
$form['my_field']['#ajax'] = array(
  'wrapper' => 'module_form',
  'callback' => 'module_form_ajax_callback',
);

The Drupal.settings array is not updated after the end of the ajax process. Seems like I'm trying to do something the Form API isn't able to do out of the box... Here's the result of the first ajax request:

You can see there's still only the submit button in the form attached to an ajax event.

Update

I spotted the issue, it was somewhere else. My form is a multi-steps form, when a step is submitted, I rebuild the form with the previous steps and add the next one.

For the previous steps, I render them based on data available from $form_state['complete form'], the render array here is actually storing a lot more data than the one I had set in the first place, which was causing conflicts.

#attached Will not be processed properly on elements that was loaded with AJAX. Maybe it could, but it never worked for me. on the other hand, using #ajax worked for me without a fault. what I would try (obviously a guess because you didn't provide full SSCCE) would be:

$field['#ajax'] => array(
  'wrapper' => 'module_form',
  'callback' => 'module_form_ajax_callback',
  'event' => 'change',
);

If this element is created with an AJAX call from another element, it's AJAX will work.


How can I use a custom table as a node type? I am reasonably new to Drupal, I have written a couple of basic modules by following the excellent videos from buildamodule.com

Now I need to somehow integrate an existing table into a drupal site.  I would like this table to be accessable as a content / node type to the rest of the drupal system.  I do not want to add this as a content type to drupal and use the table per field system drupal has as I already have the table structure and need to be able to update the data in this table from an external source.

I tried creating a new content type in a module and was able to create a schema using the schema module.  However when i use  field_create_field and field_create_instance I end up with a seperate set of fields.

How do I create a new content type in a module that can use an existing table for its data ( even if I need to provide access functions in my module)?

Is there a good tutorial somewhere that someone knows of?

While you're making work for yourself using a custom table and not the Field API, you can use your own table with

hook_node_load ( load data from custom table into node )
hook_node_insert ( insert record in custom table )
hook_node_update ( update record in custom table )
hook_node_delete ( delete record from custom table )

You'll probably also need

hook_form_alter

if you want to add form elements to the node form.

Keep in mind the Field API will do that all for you though if using standard fields.


domain access module in drupal I try to set up drupal multisite by using domain access module.we two sites sscsoftweb.com and kumba.sscsoftweb.com.Both are drupal sites which host in shared environment.i install domain access module in sscsoftweb.com. kumba.sscsoftweb.com is subdomain as per installation instruction i remove text followed after /public_html

Then i create a new domain record and create two page called page1 and page2.page1 published in sscsoftweb.com similarly page2 publish in kumba.sscsoftweb.com.i set the homepage for kumba.sscsoftweb.com is node/2.

the problem is when i hit kumba.sscsoftweb.com it automatically redirect to sscsoftweb.com homepage not to node/2. is there any thing i miss.kindly suggest me how to fix this issue.

thanks..

I played with the domain access module and I remember I had to set the cookie domain in settings.php to ".example.com", in your case ".sscsoftweb.com".
But I'm not sure this will fix your problem.


Meta Tag are not display on some of pages I adding meta tag on my site, but some of page showing page title as a Meta title,  I want to change it with other name.
But I don't know why it is not showing/Working on some of pages .

I observed that some page that connect with View those pages are only fail to add Meta tag.

Anyone know what is issue. Why I'm fail to add meta tag.

Finally i found reason behind it.

I haven't call <?php print render($page['content']); ?>.

After adding it , it is working superb.


Where do i start when trying to get webservice API's integrated? I am building a travel website for a client, and we need search form tied to different API's and in some cases combined API's returning results.

I am a seasoned PHP developer, but fairly new to Drupal.

Where should I start? what modules should i be looking at?

Any help would be great.

There is a very active group of developers working with the Services module. I am sure that another seasoned PHP developer would be welcomed by them.


hook_init called a second time on ajax I am using hook_init to check if a variable is set, and then redirect if not...

function quickstart_init() {
  if (variable_get('quickstart_admin', 0) != 1 && $_SERVER['REQUEST_URI'] != '/welcome/admin') {
    drupal_goto('welcome/admin');
  }
}

This works for logged out users, but when you are logged in, it redirects - but the whole page displays twice!

I have traced this down to admin menu, as the second version of the page only appears once that JS runs. Does anyone know if admin_menu bootstraps onload? In which case, probably run hook_init again?

Anyway, main question....

What can i do to only run this once, is there something other than hook init that would work?

You should really try to get to the bottom of why hook_init is being called twice, but for a band-aid solution, you can use a static variable (using drupal_static) to keep track of whether your implementation of hook_init has already been called.


How does Drupal know when to run an update script? How does Drupal 8 know what module needs updating and to what version he needs to update?

I have build a module and I'm trying to update it (adding a table). I implemented a update hook numbered 8001, which is the first update, but when I go to update.php Drupal does not see any update for my module.

I expect there must be a place in my module where I can define the current version of my module and another place in the database where Drupal stores the latest installed update of my module. (I need this for debugging the update script later on.)

To store/get the version information for a module use the global functions:

drupal_set_installed_schema_version()
drupal_get_installed_schema_version()

For example set a new version for mymodule with drush:

drush ev "drupal_set_installed_schema_version('mymodule', '8123')"

Print the version with drush, in this example for the module comment:

drush ev "var_dump(drupal_get_installed_schema_version('comment'))"

The functions are defined in schema.inc. Here you can see how to access the key_value table through the keyvalue api, if you want to use your own code:

/**
 * Updates the installed version information for a module.
 *
 * @param string $module
 *   A module name.
 * @param string $version
 *   The new schema version.
 */
function drupal_set_installed_schema_version($module, $version) {
  \Drupal::keyValue('system.schema')->set($module, $version);
  // Reset the static cache of module schema versions.
  drupal_get_installed_schema_version(NULL, TRUE);
}


tell drush to update anything not part of a profile I'm using an installation profile (open-outreach) and additional modules / themes.  I don't want drush to update modules that are part of the profile, but would like to update everything else.  Is there a command to do this?

This would be a good feature request for the pm-updatecode command.  I'd say that the best workaround for this missing functionality would be to tell Drush to lock the modules you do not want it to update.  Do this one time:

drush pm-updatecode --lock=project1,project2,project3

Replace 'project1,project2,project3' with a comma-separated list of all of the projects in your installation profile.  When you do this, Drush will write a lockfile into the mail directory of each project you mention, creating a persistent lock.  Thereafter, you may run drush pm-updatecode without the --lock parameter, and Drush will remember that it should not update any of those modules.

If you wish, you may also lock the modules with http://drupal.org/project/update_advanced, and Drush should respect that as well.  Works great in Drupal 6, but I have not tried Drupal 7 (only a dev release is available).


List nodes with Views 2 module, despite nodes having restricted permissions My nodes have individual Access Control permissions.

I need anonymous users to be able to see a View (giving them a preview essentially) of these nodes, but currently they don't have access.

Is there an easy way to override the permissions just for this View, and show the nodes anyway? Searching for a solution lists a workaround which only works in Views 3.

Is there any way to update to Views 3? Because in views 3, under the Advanced > Other section you can change the Query settings options and make sure the Disable SQL rewriting checkbox is checked.


How to change all hyperlinks in the content Hi i am new to the drupal and i got problem in my site in the hyperlinks.
I have book copy module by which i have created one copy of the book.
After creating the book i set aliases to content/newbook but the links in the content pointing to the old links they have not updated so i need some module which can change all hyperlinks in the content.
I have tried with views/pathauto/pathlogic/path filter but not able to solve  the problem any of these.
Please let me know if there any such module.

I am not sure if I understand the problem correctly.

But if you're looking for a module that will do a batch search and replace, replacing the path of an URL embedded in node content with another path, the search and replace scanner can do plain text search-and-replace, or regular expression search-and-replace, against the body fields on all nodes in your system.


CKEditor table td style not showing in frontend I use CKEditor (WISYWYG editor) to edit text and HTML for my Drupal project. I want to edit an HTML table and try to horizontally align text in a table cell  to the right.

My steps:

select the text in the table cell
right+click > Cell > Cell properties > Horizontal Alignment: Right.

When I am logged-in and I inspect the HTML I see My text	. But as soon as I am logged-out the HTML is stripped and I see only My text	 (style="text-align: right;" disappeared).

I certainly need to align my text to the right in some HTML table cells.

Update:

I use Filtered HTML
In admin/config/content/formats/filtered_html, I added the following settings (see screenshot):

Had a similar issue for a long text field (filtered html format).

HTML tags were getting removed when switching between formats (editor was removing them).

At /admin/config/content/ckeditor/edit/Advanced (advanced is a profile name used for the filtered html format in my case), under "advanced content filter", choosing disabled solved the issue (server side filtering works, this filtering is there for the wysiwyg ux essentially).


Can I get the raw value of arbitrary tokens? This site I'm working on is using tokens in such a way that the escaped (check_plain()'d) values provided by the tokens as is is problematic (they're getting double-escaped). Is there some way to specify that I want the raw values for those tokens? I tried just appending ":raw" to the token name, but that didn't seem to work.

I could just write my own tokens for this purpose which only provide the raw values, but I want to see if that's really necessary first.

Garrett,

From your question I can see that you have appended ":raw" to the list of tokens that you are using.

I think that will be "-raw" instead of ":raw". As example, [user:name-raw] instead of [user:name:raw].


How to terminate a batch when an error occurs I've read this: http://api.drupal.org/api/drupal/includes%21form.inc/function/batch_set/6 and through the source code, but I cannot see how a batch operation can flag that an error has occurred to show the error message.

I can set $context['finished'] = 1.0; to end the batch, but I cannot see how to set $current_set['success'] to FALSE to abort the batch and show the error message to the user.

How is this done? Is there a good example somewhere?

To set $current_set['success'] to FALSE, you can use the following code.

$current_set = &_batch_current_set();
$current_set['success'] = FALSE;

To set the messages to show to the users, you can use the following code.

$batch_context['results'][] = 'The error to be shown to the user';
$batch_context['finished'] = 1.0;

$batch_context is the last argument passed to the operation callback.

The "finished" callback receives $current_set['success'], and $batch_context['results'] respectively as first, and second argument. It can show the errors to the users using drupal_set_message().

References

_batch_process()
_batch_finished()


Need Help using hook_views_query_filter I am using hook_views_query_filter to append my own where clause condition with the where clause of the query generated by the view.

So for this I am using this hook.

Here is my code

   function mymodule_views_query_filter(&$view, $query) {
 if($view->name = "myview") {
 $query->where[1] = array(
            'clauses' => array(
                            '0'=>"field_test_value=0",

                             ),
            'args' => array('0' => 'test1', '1' => 'test2'),
            'type' => 'OR',
            );
}
print_r($query);
}

So the where clause becomes like this after print_r() funtion.

[where] =&gt; Array
    (
        [0] =&gt; Array
            (
                [clauses] =&gt; Array
                    (
                        [0] =&gt; node.type in ('%s')
                        [1] =&gt; node.status &lt;&gt; 0
                        [2] =&gt; term_data.name = '%s'
                        [3] =&gt; term_data_term_node__term_data.name = '%s'
                    )

                [args] =&gt; Array
                    (
                        [0] =&gt; test1
                        [1] =&gt; test2l
                        [2] =&gt; test3
                    )

                [type] =&gt; AND
            )

        [1] =&gt; Array
            (
                [clauses] =&gt; Array
                    (
                        [0] =&gt; field_test_value=0
                    )

                [args] =&gt; Array
                    (
                        [0] =&gt; test1
                        [1] =&gt; test2
                    )

                [type] =&gt; OR
            )

    )

Where the 0 index of the where clause is coming from the view query and the 1 index of the where is clause is coming from my code.
But it only executes the 1 index of the where clause and display the results only if Where field_test_value=1 and I want something like this.

Where (node.type in ('%s') AND node.status <> 0 AND term_data.name = '%s' AND term_data_term_node__term_data.name = '%s') OR field_test_value=0

You shouldn't alter the query objects properties directly. You need to use the methods it provides. In this case, you need to use add_where(). I think you want to consider something like this:

<?php
$clauses = array("field_test_value='%s'");
$args = array('test1');
$query->add_where(1, $clauses, $args);
$query->set_group_operator('OR'); // this is the operator that goes between WHERE groups
?>


I can't change permissions for text filters I performed a pretty massive 50,000+ node migration a few weeks ago (from Drupal 7.70 to Drupal 8.9), and just noticed today that some of the Text Filters aren't visible in content creation pages (in particular, Plain text filter, which is what I like to make the default for most fields).
I tried creating a similar filter called "Plain", but when defining the default filter for content types on text fields, though at least now the new filter is visible as on option from the select box, it won't save (it reverts back to Full HTML filter on save). Furthermore, the filter permissions page shows that something is awry as well...as I am unable to assign ANY permissions for the new filter or two of the migrated filters to any custom roles.
Clearly the migration didn't go smoothly. It took me 2 weeks to get ANY migration to work properly...so I really do no want to roll back and try again if possible. Is there any way I an fix the text filters and their respective permissions problem here?
I have full access to the server, mysql, etc. Is there something I should be looking for in particular? Or at least a DB model that I can copy?
Thanks in advance for your help.

EDIT: I just noticed that I can go into the individual user roles, and "see" the checkboxes that aren't showing up on the Permissions matrix (where you can select permissions for all users at once). Is this maybe just a rendering bug for the main permissions display page? Here's another screenshot:

This is a usability quirk of D8, in the Drupal Form UI the default format type for formatted text fields isn't configurable; it's dynamic based off form element properties (set by a developer), user role permissions, and the filter module settings (see form code)
By default, the fallback format (Plain text here) won't show as an option. There are a few things you can do here:

Set Plain text as the highest priority filter, if you want it to be the default for all formatted text fields.
Enable the always_show_fallback_choice config option (e.g. drush config-set filter.settings always_show_fallback_choice true), if you just want the format to be available.
Use the Allowed Formats module, if you need some type of per-field configuration.


Where do I find the block id for Twig Tweak module In order to print a block in a twig file when using the Twig Tweak module you require the block id, but nothing I am trying will work and I get the message that -

This block is broken or missing. You may be missing content or you might need to enable the original module.

I think your block id is a machine name of a block that you added here: Admin > Structure > Block layout (/admin/structure/block).

When you edit some block you will see the machine name. Besides, a disabled block is also allowed.


What is the URL for configuring OAuth2 services? If this is the code in oauth2_servers.services_auth.inc module, what is the url to enable the "require authentication" checkbox?

/**
 * Services authentication "controller_settings" callback.
 */
function oauth2_server_services_controller_settings($settings, $controller, $endpoint, $class, $name) {
  $form = array();
  $form['require_authentication'] = array(
    '#type' => 'checkbox',
    '#title' => t('Require authentication'),
    '#default_value' => isset($settings['require_authentication']) ? $settings['require_authentication'] : FALSE,
  );
  $form['scope'] = array(
    '#type' => 'textfield',
    '#title' => t('Scope'),
    '#default_value' => isset($settings['scope']) ? $settings['scope'] : '',
    '#description' => t('A space-separated list of required scopes. Leave empty to ignore the check.'),
  );

  return $form;

You enable OAuth2 authentication in admin/structure/services/list/$yourserver, then on the Authentication tab (admin/structure/services/list/$yourserver/authentication) you select the OAuth2 server.
After that, once you go to the Resources tab (admin/structure/services/list/$yourserver/resources) you will see the mentioned settings in the Settings column for each resource.

Make sure that you have the latest -dev release of Services, or the patch mentioned on the OAuth2 Server project page applied, otherwise it won't work.


How to output node fields of referenced nodes as plain-text key/value pairs? I've got a super content-type that contains at least 4 node references.

The first three references aren't always the same node-type but they contain just one referece.

The third reference can contain multiple references which are all of the same type but the type of these references my differ from time to time.

The forth reference references only one node each, which hast always the same type.

So I have a super node which references a few other nodes where number and node-type are not always the same. That's my starting point.

Now I have to send the whole content e.g. the custom fields I've created in the content-types of the sub-nodes via e-mail every time new content is created. The email should be plain text and should contain key/value pairs of the custom fields.
The format is "key: value". This is fix my customer requires it and I can't change this at the moment.

To do this I want to use rules + views + rules_views (Rules Views Integration) and this is the point where I'm unsure what is the best way to continue. I pass the node-id from rules to views to render the just created node.
If I tell views to use "row style: node" and choose "full node" as "display", I got my super node with all the sub nodes inside fieldsets.

Basically thats very close to what I want and it looks like I just have to theme my node to get rid of all the HTML an plain text but how?

Do I have to use my standard node-'node-type'-tpl.php files or can I add tpl.php-files just for this specific view?
Or is it possible to add a different display besides 'teaser', 'full node' and 'rss' that views will recognize and that I can theme to my liking?
And if one of these is the way to go, how can I pass arguments from views to my tpl.php-file to decide how to lay out my node (for display on the site or for the email via rules)?

I hope this all makes enough sense and you can help me out.

Thx in advance.

mantuko

Finally I got that one too :)

One can add build modes with the Build modes module an decide on $node->build_mode what to render.

In the node-"super node".tpl.php one gets the node-ids of the referenced nodes from $node. Then one can node_load() these nodes into a variable and theme them.


How to properly attach a library to CheckoutPaneForm I'm attempting to attach a library to a CommerceCheckoutPane plugin.  I first started with using $pane_form['#attached']['library'][] = 'commerce_paypal/express-checkout';.  There were some errors in my commerce_paypal.libraries.yml file but once those were resolved the libaries still don't appear to be loaded.

Right now, my setup looks like:

commerce_paypal.libraries.yml:

paypal.checkout:
  remote: https://www.paypalobjects.com/api/checkout.js
  license:
    name: MIT
    gpl-compatible: true
  js:
    https://www.paypalobjects.com/api/checkout.js
express-checkout:
  js:
    js/paypal_ec.js
  dependencies:
    - commerce_paypal/paypal.checkout

Drupal\commerce_paypal\Plugin\Commerce\CheckoutPane\ExpressCheckout:

public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
  $pane_form['#theme'] = 'commerce_paypal_express_checkout';

  return $pane_form;
}

commerce-paypal-express-checkout.html.twig

{{ attach_library('commerce_paypal/express-checkout') }}

asdfas

js/paypal_ec.js:

console.log('here');

When I place the pane form I see asdfas but the JS is not added.  I've checked the source, no sign of paypal_ec.js.

As usual, I was messing something up.  JS libraries need : {}.  Updating commerce_paypal.libraries.yml to this solves it:

paypal.checkout:
  remote: https://www.paypalobjects.com/api/checkout.js
  license:
    name: MIT
    gpl-compatible: true
  js:
    https://www.paypalobjects.com/api/checkout.js: {}
express-checkout:
  js:
    js/paypal_ec.js: {}
  dependencies:
    - commerce_paypal/paypal.checkout


Show a Particular Page in Drupal 7 Table Pager I have a table and a table pager in my form.

// $table_rows is an array containing data.
$page = 2;
//$page indicates that I want to display the second page in the table pager
//$page is dynamic. It depends on the user.
$per_page = 5; //No. of items per page
$chunks = array_chunk($table_rows, $per_page, TRUE); // Split an array into chunks of $per_page

$html =  theme('table', array('header' => $header, 'rows' => $chunks[$page], 'sticky' => TRUE)) . theme("pager", array('quantity',count($table_rows)));

The result of my code is below:

It works fine as expected , but my pager number is not. It must  show 2 as the current page. Where am I missing?

I think theme_pager in your case never know about current page, by which it can decide where to add 'page-current' class.

Try passing 'element' parameter the way you are doing for quantity.

$html =  theme('table', array('header' => $header, 'rows' => $chunks[$page], 'sticky' => TRUE)) . theme("pager", array('element'=> $page, 'quantity',count($table_rows)));

While $page will be less than a value of actual current page value. Please see theme_pager to see how it works.


What tables are affected by "drush cc all"? What database tables are affected from drush cc all?
Obviously, I could gather all the tables starting with cache_.

Is there any other table that is affected by this command?

The list is dynamic, there's a convention to use cache_ as a prefix but it's not enforced. Modules can implement hook_flush_caches to register names of tables to clear:

  This hook allows your module to add cache table names to the list of cache tables that will be cleared by the Clear button on the Performance page or whenever drupal_flush_all_caches is invoked.

So basically the answer lies in the code for the modules you have installed, and you'll need to invoke that hook to get an accurate list of tables used as cache bins.


How to handle the 'Save and edit' form action? I'm copying code from a module that does more or less what I want. However, the module I'm copying has a bug... The form we're trying to extend has both a 'Save' button and a 'Save and edit' button. The following code only seems to work when the 'Save' button is pressed, not when the 'Save and edit' button is pressed...

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

  $environment = reset($form_state['build_info']['args']);
  $is_external = apachesolr_environment_variable_get($environment['env_id'], 'is_external', FALSE);

  $form['make_external'] = array(
    '#type' => 'checkbox',
    '#title' => t('Make this environment external'),
    '#default_value' => $is_external,
  );

  $form['actions']['save']['#submit'][] = 'x_environment_edit_submit';
}

function x_environment_edit_submit($form, &$form_state) {
  if ($form_state['values']['make_external']) {
    apachesolr_environment_variable_set($form_state['values']['env_id'], 'is_external', TRUE);
  }
  else {
    apachesolr_environment_variable_del($form_state['values']['env_id'], 'is_external');
  }
}

The way I do it is to add extra parameters, like:

$form['actions']['save']['#machine_name'] = 'save';
$form['actions']['save_edit']['#machine_name'] = 'save_edit';

Button position in $form found here.

Then in submit handler I can use:

switch($form_state['triggering_element']['#machine_name']) {
  case 'save_edit':
    // some code
  case 'save':
  default:
    // come other code
}

Alternative method:

Note that both buttons have submit handlers attached directly to them:

$form['actions']['save'] = array(
  '#type' => 'submit',
  '#validate' => array('apachesolr_environment_edit_validate'),
  '#submit' => array('apachesolr_environment_edit_submit'),
  '#value' => t('Save'),
);
$form['actions']['save_edit'] = array(
  '#type' => 'submit',
  '#validate' => array('apachesolr_environment_edit_validate'),
  '#submit' => array('apachesolr_environment_edit_submit'),
  '#value' => t('Save and edit'),
);

So, in your own code you can append submit functions separately. Assuming you wish to keep original ones executed, in your form alter use something like:

$form['actions']['save']['#submit'][] = 'x_environment_edit_save_submit';
$form['actions']['save_edit']['#submit'][] = 'x_environment_edit_save_edit_submit';

and of course create these functions.


How to make Drupal 6 search result URL use "-" instead of space? Example of Drupal 6 search result URL is like this:

http://www.site.com/search/node/Search for something

How to make Drupal 6 search result URL use - instead of space? (below is an example):

http://www.site.com/search/node/Search-for-something

You could add the functions custom_url_rewrite_inbound() and custom_url_rewrite_outbound() in the settings.php.

custom_url_rewrite_outbound() would rewrite the URLs which are output from any module, and custom_url_rewrite_inbound() would rewrite the URL being requested to Drupal.

This is the example code used in the documentation of custom_url_rewrite_outbound().

function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
  global $user;

  // Change all 'node' to 'article'.
  if (preg_match('|^node(/.*)|', $path, $matches)) {
    $path = 'article' . $matches[1];
  }
  // Create a path called 'e' which lands the user on her profile edit page.
  if ($path == 'user/' . $user->uid . '/edit') {
    $path = 'e';
  }
}

In your case, the code could be something similar to the following one.

function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
  if (preg_match('|^search(/[^/]+/(.+))|', $path, $matches)) {
    $path = 'search/' . $matches[1] . str_replace(' ', '-', $matches[2]);
  }
}

custom_url_rewrite_inbound() should do the exact opposite.
The code I wrote does not consider the case the - is included in the search string. The code should consider that case, for example adding another - where there is already one; when it does the opposite operation, the code should first replace a single - with a space, and then remove a - where there are more of those characters in row.


Module config page linked on Management Toolbar I created a config page for my new module.  Whenever I enable the module, a link to the config page is added to the Management menu across the top of the screen as well as a configure link next to the module name in the Modules page.  How do I configure this page so that it just shows up with the configure link on the modules page and not in the menu.  Below is the code from hook_menu:

$items['admin/mymodule/settings'] = array(
  'title' => 'mymodule Module Configuration',
  'description' => 'Settings for my module',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('_mymodule_admin'),
  'access arguments' => array('administer mymodule settings'),
  'type' => MENU_NORMAL_ITEM,
);

The module has a function called _mymodule_admin that returns a form array.  The config page works great. I just want to prevent the link from appearing on the management menu when the module is activated on my production site.

My info file contains the following line

configure = 'admin/timesdb/settings'

And my form callback has includes this line

return system_settings_form($form);

With the relevant form elements assigned above it.

It is because you have added a MENU_NORMAL_ITEM under the admin menu, so it will automatically put it in the admin toolbar (that is also the default so if you exclude that parameter it will also be a menu normal item).

If you change it to MENU_CALLBACK, that will create the link between that url and your page callback, but it will not create an item in the menu.

See hook_menu() for all the menu item types.


How do I make a link to a flag edit page? I'm using Drupal 8 with Flag 4.0-beta1.
On my flag, I have several fields.  I want users to be able to edit these fields after making the flag.
How can I make a link to the flag edit page?
I found this comment on using VBO for Drupal 7, but on Drupal 8, VBO doesn't have the "modify entity" option for flaggings suggested in that post.
I tried various things in Views (making a view of flaggings; making a view of nodes with flaggings as a relationship), but I can't find a way to get an edit link.
EDIT: I got confused by the terminology and mixed up flags (the "type") and flaggings (the instance of the type) are different.  I'm leaving this question as is, and I created a new question for flaggings.

I'm not sure about any view field for an edit link, but you can link to the flag's edit screen, like most entities, in a number of ways.
Looking at the module's flag.routing.yml file, we see the edit route defined like:
entity.flag.edit_form:
  path: '/admin/structure/flags/manage/{flag}'
  defaults:
    _entity_form: flag.edit
    _title: 'Edit Flag'
  requirements:
    _entity_access: 'flag.update'

The flag argument here is for the flag's id.
You can build out the link to the flag manually, e.g.
Edit MY FLAG

Or if you're working with twig, e.g. rewriting a view's field, make sure you're also including the flag's id in the view then rewrite doing something like:
{{ "Edit"|t }}

Or you can use PHP to build the url directly from the route. It's recommended to use one of the following methods if you're working in PHP.
To get just the url text or object in PHP, use Url::fromRoute():
use \Drupal\Core\Url;

$my_flag_url_object = Url::fromRoute('entity.flag.edit_form', ['flag' => MY_FLAG_ID]);
// $my_flag_url_string returns something like "/admin/structure/flags/manage/123"
$my_flag_url_string = $my_flag_url_object->toString();

To build the whole link in PHP, use Link::createFromRoute():
use \Drupal\core\Link;

$my_flag_edit_link = Link::createFromRoute('MY FLAG EDIT TEXT', 'entity.flag.edit_form', ['flag' => MY_FLAG_ID]);


How to hide a content type on the node add page? I need a way to hide a content type on the node add page, or better yet, make two separated node add pages that separate my content types. I'm on Drupal 7 and have four different content types. I would like three of them to be on the default node add page and the fourth to be separate. How would I do this?
Thanks

Two possibilities:

admin/structure/menu/manage/navigation move/delete menu item that you don't want.
Cleanest way: use roles and permissions. If the user can't create a content type the link will not appear in any menu.


Custom text/html in custom form module I am following this tutorial and I've already created my custom form as Drupal 8 module.

I wonder, how to add custom text/html in form? I mean when somebody goes to the path pointed in *.routing.yml, I would like to display not only form fields, but also some intro html/text.

I know the form building is here:

public function buildForm(array $form, FormStateInterface $form_state) {

$form['name_surname'] = array(
  '#type' => 'textfield',
  '#title' => t('Name and surname:'),
  '#required' => TRUE,
);
...
}

But I don't know what kind of entry (or #type) should I insert to get just an custom html/text block between fields or above them all?

What kind of entry (or #type) should I insert to get just an custom
  html/text block between fields or above them all?

Item element type provides a display-only form element with an optional title and description.

$form['help'] = [
  '#type' => 'item',
  '#title' => t('Block title'),
  '#markup' => t('Block content'),
];

You may also add arbitrary content to render arrays using the #markup render array key as follows.

$form['text']['#markup'] = t('Some text.');


How to customize profile2 module profile edit form using template method? How to customize the profile edit form of the Profile2 module using a  template?

Profile2 has the main profile (admin/structure/profiles/manage/main), and it is set to provide a separate page for editing profiles (profile-main/1/edit).

In Drupal 7, for a content type such as faq, I can use a template to customized its edit form.

In template.php, I am using the following code:

function MYTHEME_theme(&$existing, $type, $theme, $path) {
  return array(
      'faq_node_form' => array(
      'arguments' => array('form' => NULL),
      'template' => 'node--faq--edit',
      'render element' => 'form',
  ),
  );
}

I then create node--faq--edit.tpl.php, where I can customize it.

What is the equivalent method I could use for a Profile2 profile edit form?

You should use form_id as theme key in hook_theme(), which is user_profile_form in the case.
function MYTHEME_theme(&$existing, $type, $theme, $path) {
  return array(
    'user_profile_form' => array(
      // …
    ),
  );
}

See Theme Profile2 Form, a support request opened for the Profile2 module.


user/%/edit - remove it from tab and make it an actual menu item I am pretty clueless on how drupal handles such things and I can't seem to grasp the context.

I want a menu link to user/%/edit (using menu token already). But as it seems /edit is a 'tab' item of the user/% menu (also saw it in the db). Using theming I have visually removed the unwanted tabs and I've also merged the user/edit form with the profile2 forms I need for extra fields using form_alter.

The problem is that even though I have a menu link called "My Account" linking to user/%/edit,
whenever I click it to go there, the "Edit" menu link appears as active in my main menu instead of the "My Account".

Is there any way to remedy this?

If the question is not clear I will revise it cause it's a pretty confusing issue.

EDIT: to avoid similar answers, the problem is not how to visually remove the tabs, the problem is how to somehow alter or ignore the user/* menu structure so the "Edit" part is not a separate tab anymore and thus it won't show when I click the link that leads to to user/%/edit

You want to alter the original menu item that was defined in user.module's hook_menu(). You can do this in hook_menu_alter().

The item's array key is simply the path, so:

function hook_menu_alter(&$items) {
  $items['user/%/edit'] = array(
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'my_custom_page_callback',
    'page arguments' => array(1),
    'access callback' => TRUE,
  ),
}


How to get plain link with views-data-export module in CSV? I have a view with field that provides a simple link to the content.

Problem: When I export the data into a csv file there is only the word link instead of a link.

How can I get there the content URL instead of the word link?

CSV is not an interactive format. When you export column with literal "link" in it's data, you get link in CSV.

Instead of exporting word column, with link added at rewrite or template level, export column that actually contains the URL you want. For nodes, this issue indicates that you should be able to use 'Path' field, description: 'The aliased path to this node.'.


Change node author with Rules I have field in content type called field_new_author which is User reference field.

I need to make a Rule to change Node author field to match value in field_new_author.
I tryed this solution: Change node author on node save with rules

But I'm getting database error:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '4141-0-all' for key 'PRIMARY': INSERT INTO {node_access} (nid, realm, gid, grant_view, grant_update, grant_delete) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5); Array ( [:db_insert_placeholder_0] => 4141 [:db_insert_placeholder_1] => all [:db_insert_placeholder_2] => 0 [:db_insert_placeholder_3] => 1 [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => 0 ) in node_access_write_grants() (line 3440 of /home2/test/modules/node/node.module).

I also tryed different setups in Rules but could not find anything that would work.

I assume you are using D7 with Entity Reference.  You should be able to do this with stock Rules, without any PHP code:

Create a new rule
Event, select "After updating existing content"
Condition, select "Content is of type" to match whatever content type it is.  This will qualify the fields so that you can use them later
Condition, select some other limiting condition so that you don't target every single node with updated content.  You could, for example, do a data comparison to check if the content has a given taxonomy term
Action, select "Set data value".  Your target should be node(updated content):author.  Your new value should be node(updated content):field-new-author


What does a value like node:{node_type} mean? I'm trying to fully understand Drupal 8 routing. I understand the basics, no problem, but some of the finer details are still a mystery.

Here's the route for adding a node from the node module.

node.add:
  path: '/node/add/{node_type}'
  defaults:
    _controller: '\Drupal\node\Controller\NodeController::add'
    _title_callback: '\Drupal\node\Controller\NodeController::addPageTitle'
  requirements:
    _node_add_access: 'node:{node_type}'
  options:
    _node_operation_route: TRUE
    parameters:
      node_type:
        with_config_overrides: TRUE

I'm struggling with the line _node_add_access: 'node:{node_type}'.

I understand what the _node_add_access key does. It refers to a service with a tag of applies_to: _node_add_access. That is provided by the NodeAddAccessCheck class.

What does the node:{node_type} do?  No amount of tracing through code has answered that for me. It looks to be a unique value for some purpose. Is it related to caching?

I haven't got to the options stuff yet.

Thanks

EDIT: I'm not sure if this should be an answer but these applies_to requirements seem to be read in Drupal\Core\Access\CheckProvider::applies and the value (e.g. node:{node_type}) doesn't seem to be used at all.

That definition isn't about what is passed to NodeAddAccessCheck, that is solely defined by the slug definition in the path and the type hinted argument.

Instead, it is configuration for its implementation. Which it doesn't actually use. So yes, it is pointless. See \Drupal\Core\Entity\EntityCreateAccessCheck for an access check that actually uses that definition to dynamically get the value it wants from the route match parameters.

I suppose this initially used that and was switch to a different implementation, without removing the now unnecessary configuration.


Can Joyride Jquery Button take us to another page?

Stop #1

We will see this on first stop(Ask saheel what to be written   here).     Any valid HTML will work inside of Joyride.

Update Events

We will see is some random things about Upcoming Events Here too.

Final Closing

If it works fine, we have Achieved Level 3

Recent Article

**
We will see whether this page would take us there.Go to Desired Page
**

I have written this code but what I want is, jquery Joyride should take the user to another page when the last pop up has appeared and user clicks on it's button where an automatically triggered action would run. So far I am unable to do that. Is it even possible?
PS: ****** would be replaced by the desired page address.

I'm not sure about joyride but you could write some javascript to listen for when the last popup  has appeared and afterwards use

window.location.href = 'someurl.com';

Or some such to move the user to a new page.


Dynamic "My Account" text in navigation menu How would I go about modifying the "My account" text in the navigation menu, to link the title to a title callback?

My goal is to have "My account" say "My premium account," "My guest account," and so on when an applicable user is logged in. For most menu items, this would be easy to do with hook_menu_alter and a title callback.

But, hook_menu_alter doesn't seem to effect this menu item at all.
Any ideas?

Drupal caches menu items, so if you're using hook_menu_alter you'll need to clear the menu cache to make your changes apparent.  For your requirements, hook_menu_alter is no good anyway, as the menu has become dynamic!

My suggestion would be to use Menu Per Role.  Create one menu that has each of your required menu titles in as seperate menu items (ie one menu containing three menu items; one for each type of account) and then restrict the visibility of those menu items to users with particular roles.

eg

My Account Links

My Account - only visible to standard users
My Guest Account - only visible to guest account holders
My Premium account - only visible to premium account holders

When set up correctly, this will only display one link per user (although when logged in as user 1 you will see all links).


Override and add a link to a themed table Using a custom module, I'm trying to add "Schedule" links to each of the rows of the table on node/%nid/revisions, but can't seem to figure it out.  Do I have to override the entire function node_revision_overview in node/node.pages.inc?

There is another table I would like to this to as well.  So in general, I thought this would be a good excercise to learn Drupal theming.

Any help is appreciated.

yes copy the whole function to one of your own and add the operation. this is not dynamic.

for the other table, if you use an entity you could add the operation via the entitycontroller, only found this for d8 in the rush .. Custom entity operation links

for the d7 way http://drupalcontrib.org/api/drupal/contributions!entity!includes!entity.ui.inc/class/EntityDefaultUIController/7


How can I fix the node list page broken by changing the reference field from a term reference to an entity reference This answer explains the set up I currently have.  I have cloned the Taxonomy Term view built into views, and added some extra filtering etc. To create a depth aware list of nodes for taxonomy terms as linked by pathauto (pattern pub/by/[term:vocabulary]/[term:name]).  So for example previously a link to /pub/by/publisher/asian-development-bank would provide me with a list of nodes that had associated Asian Development Bank in a term reference field with the node.

This is site is bilingual, and the publisher vocabulary has an acronym field, and on the node creation form, I needed the autocomplete to return results for the name entered in either English or Japanese, or the acronym.(more detail in this question) Which required me to change the fields referencing the publisher vocabulary to be entity reference fields instead of term reference fields.

The problem is that now /pub/by/publisher/asian-development-bank is an empty list.  I'd like to override /path/by/publisher/% links to use an entity reference relationship to search for the term rather than the means that the default Taxonomy Term view does.  The issue is that the path in the Taxonomy Term view is /taxonomy/term/% utilizing the value coming from the destination query variable.

How can I create a view that will still use those links generated by pathauto, but actually return results from the entity references?

Just to complicate things a little, each node has two entity reference fields to the publisher vocabulary: field_doc_copyright and field_doc_publisher

I got it.  I had initially been trying to create  a new view to operate on the /pub/by/publisher/% path, but I realized by inspecting the view, that the view I already had on /taxonomy/term/% was handling the route because links to one of the pathauto generated routes end up being to the equivalent of /pub/by/publisher/term-name?destination=/taxonomy/term/tid

The problem is then to get the existing view to show the results I want.  In my case, since the existing view was showing no results for any publisher vocabulary term, and publisher terms should be the only terms that return results for my new view; I had the option of adding an attachment or other view in the no results section or to just create an attachment attached after the main view.  I added an attachment and added it after the main view.  Since I needed the results of two entity reference fields I needed an OR condition between my contextual filters.  For this I used Views Contextual Filters OR.

One additional problem I faced was that my filters and contextual filters were being joined with an OR condition rather than an AND condition, meaning that I was effectively querying for public nodes or the right type OR the nodes I actually want, which returned way more results than intended.  The solution for this, was to add a new empty filter group to my attachment, joined to the original filter group with an AND condition, this caused it to start joining my contextual filters with AND as well.

Finally, my main view had some exposed filters on it, but thought I had inherit exposed filters checked on the attachment, those exposed filters were not working.  It turns out that you need to add the same exposed filters to the attachment before the inheritance on them will work.

I doubt many people will have exactly the same problems I had, but hopefully it will provide a clue for people with something similar.  As seems to always be the case @no-sssweat was instrumental in providing the hints I needed to get to the answer.  Thank You!


hook_views_data and DECIMAL columns I have an external database that I am wiring into views with hook_views_data().  This particular database is making use of DECIMAL data type.  What are the proper field, filter, etc, handlers to use with this?

The 'numeric' type classes handle both integers and floats/decimals:

Field handler: views_handler_field_numeric
Filter handler: views_handler_filter_numeric
Argument handler: views_handler_argument_numeric
Validation plugin: views_plugin_argument_validate_numeric

It's not that obvious at face value, but if you look at the comments for views_handler_field_numeric:

Definition terms:

float: If true this field contains a decimal value. If unset this field will be assumed to be integer.

So setting 'float' => TRUE on your field definition, and using the numeric handlers, is all you need to do. e.g
$data['some_table']['msrp'] = array(
  'title' => t('MSRP'),
  'help' => t('MSRP of the product.'),
  'field' => array(
    'handler' => 'views_handler_field_numeric',
    'click sortable' => TRUE,
    'float' => TRUE,
  ),
  'filter' => array(
    'handler' => 'views_handler_filter_numeric',
  ),
  'sort' => array(
    'handler' => 'views_handler_sort',
  ),
);


Placing Panels Content Above Menu I am trying to use panels to implement something that in the past I had done with blocks. My theme has a region called "content top", this displays content above the secondary menu (the tabbed menu that every node has with view edit etc). When I switch over to panels, I can't figure out how to place content in any other region except for the main area ... any ideas

Panels are page nodes and can not be put into regions as we do with blocks. Try mini panels to create panels for regions or itself panels.


anonymous User broken I just migrated the site from sqlite to Postgres, using the drush portabledb-import module

I'm getting a error page only when no user is logged in to the site.

I can get logged in using the login-link generated running

drush user-login

and everything works great, all the content is there and accessible, views all work, etc...
however log out and I get this message at the home page again

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

and The watchdog-show reports this

 ID         :  8
 Date       :  12/Mar 13:07
 Type       :  php
 Severity   :  error
 Message    :  PDOException: SQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for integer: "not yet assigned"
               LINE 4: WHERE  (base.uid IN  ('not yet assigned'))
                                             ^: SELECT base.uid AS uid, base.name AS name, base.pass AS pass, base.mail AS mail, base.theme AS theme, base.signature AS signature, base.signature_format AS signature_format, base.created AS created, base.access AS access, base.login AS login, base.status AS status, base.timezone AS timezone, base.language AS language, base.picture AS picture, base.init AS init, base.data AS data, base.uuid AS uuid
               FROM
               {users} base
               WHERE  (base.uid IN  (:db_condition_placeholder_0)) ; Array
               (
                   [:db_condition_placeholder_0] => not yet assigned
               )
                in DrupalDefaultEntityController->load() (line 191 of/usr/local/www/main/includes/entity.inc).

I've checked the DB and the 0 uid looks fine
but just in case I followed the "Restore the anonymous (user ID 0) user record docs located here
https://drupal.org/node/1029506

any ideas or suggestions would be greatly appreciated.

I don't think you can migrate like that.  I am pretty sure the database creation during installation process is different if you're using postgres.


Node showing teaser, but not content My view is showing the list of teasers correctly, but when I want to read more and see the full body text I get the "Page not found" error. I've been searching through all my settings, permissions etc. and can't find the error. It might have something to do with the view, but I can't see any error there either. Any ideas?

Screenshot of the view settings:

I can easily find the node body in the MySQL table field_data_body.

I have an alternative solution in case it is not working. Include title, body (trimmed) and global text contain

Read More

Make sure include node path and drag it above so that it appears in replacement pattern down below


When reimplementing Drupal.tableDrag.prototype.dropRow(), how do I access classes of would-be parent? Using code below, I can access classes of a row that's being dropped:

Drupal.tableDrag.prototype._dropRow = Drupal.tableDrag.prototype.dropRow;
Drupal.tableDrag.prototype.dropRow = function(event, self) {
  console.log('dropRow');
  console.log("feature-group: " + $(self.rowObject.element).hasClass('feature-group'));
  console.log("feature: " + $(self.rowObject.element).hasClass('feature'));
  if ( /* use classes here */ ) {
    /* return custom result here */
  }
  /* fallback to default here */
  return self._dropRow(event, self);
};

But now I don't want to test classes of a dragged row, but ones of a row that would be a parent. How do I do that?

To clarify: I need tabledrag parent, not DOM parent. All tabledrag rows are DOM siblings, and I need the row with ID field value equal to the would-be Parent ID field value (class="parent") of a dragged row.

Something in JavaScript sets the parent ID properly, during either drag or drop (can't tell), so I'm sure there is a way. I just don't know how to find it.

Get a reference to some parent DOM element ... the jquery parents() or parent function(s) comes to mind. Then use hasClass on those parents as needed.

some parent would be something like the following based on your example:

var parents = $(self.rowObject.element).parents(/* a selector to limit the type of parent, td, tr, whatever */);

EDIT:

dragged rows get a class of like .dragged-previous. The file tabledrag.js doesnt care about the current row, nor about IDs of anything during drag -- its just doing a DOM swap of rows and inserting the dragged row before another row; and assigning a Drupal weight to the hidden weight column. So cant you use like jquery prev() function to get the immediate previous element:

var parent = $('#menu-overview tr.drag-previous').prev();

I'm taking these values from a Main Menu tabledrag example of a vanilla D7 site:


Error when importing the configuration We have several sites running with Drupal.
On my local machine I run the test versions of each site in the Docker container to add new features or test new ones.
When switching between pages I do the following.
Shut down the container of page-A.
Change to the directory of page-B, start the container.
Then execute the following commands in the terminal in the container:
composer clearcache
composer install
drush sql-drop --yes;
drush sqlc < page-B_init.sql
drush updb
drush cim

When running drush cim, the following error message appears:
 [error]  Drupal\Core\Config\ConfigImporterException: There were errors validating the config synchronization.
Entity type mismatch on rename.  not equal to configurable_language for existing configuration system.site and staged configuration language.entity.en.
Rename operation for simple configuration. Existing configuration system.site and staged configuration language.entity.en. in Drupal\Core\Config\ConfigImporter->validate() (line 755 of /var/www/html/docroot/core/lib/Drupal/Core/Config/ConfigImporter.php).

In ConfigImportCommands.php line 261:

  The import failed due to the following reasons:
  Entity type mismatch on rename.  not equal to configurable_language for existing configuration system.site and staged configuration language.entity.en.
  Rename operation for simple configuration. Existing configuration system.site and staged configuration language.entity.en.

I suspect the problem is with the UUID, which I have in the files:
environments/_default/config/sync/system.site.yml
environments/_default/config/sync/language.entity.en.yml

adapted.
But I don't know any further.
Does anyone have an idea where the error lies?
Use Drupal 8.9.13

This might not be the best way, but I had this same issue today. I ended up renaming language.entity.en.yml to include .OLD at the end of the filename for a backup, then I re-ran drush cim. After that it accepted my system.site.yml file. Then I took a look at the language.entity.en.yml file and for some reason it had the exact same UUID as the system.site file. I suspect the import is confused about which file is which because they both had the same UUID.


Including image styles in custom module I was following topic. I can including image style in my custom module. But I have a problem. I can't reinstall module because of following error:

  Unable to install Module ABC, image.style.black_white already exists
  in active configuration.

Can I include an image style in custom module with file config and maybe reinstall module?

Your problem is don't delete image style when uninstall module. So when you reinstall image style already exist. Use can use hook_uninstall to delete
image style to finish uninstall: write code in file module_name.install

<?php
use Drupal\image\Entity\ImageStyle;

function module_name_uninstall() {

  ImageStyle::load('image_style_name')->delete();

}


How can I change the  on a View filtered by NID so that it is the referenced Node's Title field? I have a view which only displays a single result and I am using NID as the contextual filter. I cannot change that, it needs to be NID.

I want my page <title> to be the "Title field" of the node that was filtered rather than its NID.

As it is, in my contextual filter I can "Override title" by typing in "%1" which results in the terrible <title>1234 | My Site</title>. Assuming node/1234 is titled "John Doe", I want my title to be <title>John Doe | My Site</title>.

How can I accomplish this?

You need to "Specify validation criteria" in your contextual filter.

In your Contextual filter scroll down and check the box "Override title" but leave the text box empty.

Next, check the box "Specify validation criteria" and select "PHP Code" from the validator menu.

In the code box enter the following:

if($argument) { // Check that argument is present
    $myNode = node_load($argument); // Load node based on NID
    $myTitle = $myNode ->title; // Parse node data to get title
    $handler->options['title'] = $myTitle; // Change the view's page title to node's title
}
return true;