How to access values from earlier steps in multi-page Webform? I'm using Webform 4. It uses Drupal's tokens, not it's own % tokens like it used to in version 3, and pretty much all what I found was about webform 3.

Say I want to make multi-page subscription form. On first page there is only an email field. On second one, I want a markup that will say something like:

  Detailed subscription configuration for molot@example.com

Similarly, I'd like to be able to use them as default values for future fields, like asking user for billing address, and then for delivery address.

Are there any tokens for that? What I did for now is:

function mymodule_token_info() {
  $type = array(
    'name' => t('Webform submitted values'),
    'description' => t('Tokens related to $_POST[\'submitted\'].'),
  );
  $tokens = array();
  if(isset($_POST['submitted'])) {
    foreach($_POST['submitted'] as $key => $val) { //discard $val now
      $tokens[$key] = array(
        'name' => $key,
        'description' => "\$_POST['submitted']['$key']",
      );
    }
  }
  return array(
    'types' => array('webform_submitted' => $type),
    'tokens' => array('webform_submitted' => $tokens),
  );
}

function mymodule_tokens($type, $tokens, $data, $options) {
  if($type == 'webform_submitted') {
    $replacements = array();
    foreach ($tokens as $name => $original) {
      //Hide errors below. We don't care if it really exists yet. If empty, so be it.
      @$replacements[$original] = (string)$_POST['submitted'][$name];
    }
    return $replacements;
  }
}

It works, but it only shows values from one step earlier, so requires some dirty tricks with hidden fields to carry email value across multiple steps. I admit - it was just quick and dirty. Is there any built-in way to do it, or properly maintained contributed module for this? Or a way to make this code work independently of $_POST['submitted'], to make it carry values across many steps and to make it's tokens (from available Webform elements) visible on token list in edit windows?

This does not answer the question in your title, but reading your use case it sounds like the scenario that Profile2 was written for.  Related stackoverflow post

Webform is great for surveys and such, but when you want "to be able to use them as default values for future fields" they need to be connected to the user.  So you would then need more custom code to fetch the user's historic webform submission to pull these values in a form alter for your billing address.  Profile(2) is written precisely to make this easier.

Also, the less last-minute custom coding you are doing before handing this off to some one else, the less that some one else will curse you in their heart when they are trying to make updates.


Updating core to a newer version I can update Drupal 7 websites core with following instruction  from "How to update Drupal core".

Make a backup of your Drupal instance (database). (For ex: with MySQL)
Download the latest release of your current Drupal version.
Extract the [tar ball or zip] Drupal package.
Set your site on maintenance mode (For ex: How on D7)
Delete all the files & folders inside your original Drupal instance except for /sites and its sub-folders. This assumes that all of your custom work - including themes - is in the recommended spot - the /sites folder tree. If you have made custom changes elsewhere you will need to either preserve them or plan to replace them later.
Copy all the folders and files except /sites from inside the extracted Drupal package [tar ball or zip package] into your original Drupal instance location.
Some updates do not include changes to setting.php and some do. See There is a way - Comment below for more on this. If the update release includes changes to settings.php you will need to replace your old settings.php in .../sites/default/ with the new one, and then edit the site-specific entries (eg database name, user, and password) in the setting file.
If you have modified files such as .htaccess or robots.txt re-apply those changes to the new files.
If you have a favicon.ico file that was deleted replace it too
Login to your site as administrator or as user no 1
Run update.php by navigating to http://...yourdrupalsitename/update.php and follow the process to update your Drupal instance
Disable maintenance mode

I want to know the instruction for updating Drupal 8 core (e.g. from 8.0.0 to 8.0.2). How do I do it?

Download drupal 8.0.2
Extract
Copy the core directory into your project.
Copy the .htaccess , composer.lock & composer.json files to your project
Copy the vendor directory to your project
Go to yoursite.com/update.php
Follow the on-screen instructions

Note: if you use composer then see my answer to this question


How to deploy a site with open source? I created a Drupal 7 site on my localhost. I installed some modules, created some content types and fields, changed some preferences, etc. and also entered some real test data. (I want this data to be preserved when I will copy the site to the production server.)

When the first alpha release will be ready I am going to copy the site to a production server in Internet.

I like the idea to make the software behind my site open source. This way I could be able to receive patches from other developers. (And also the possibility exists that somebody may use my engine for his other site.)

How to manage development of my site?

If it would be a framework, I would be able to do it with SVN or Git for all files + database change scripts. But Drupal also has an admin interface, which I don't know how to put under version control.

Also, how to release an open source package? I need include there some database creation script. Should I just export my DB? (only structure no data?) and put some SQL script into my .tar.gz?

Detailed description of deployment of an open source package for Drupal would be welcome.

Also: Could anyone explain how to use "Features" package in this situation?

To migrate your database (including the configuration of the admin interface) from the staging to production server, check out the Backup and Migrate module.

RE: your question about "Open source":

Unless your configuration is something really special, with a specific target audience and use case, it may not be worth your while making your configuration, etc. available for others, but YMMV.

If you want to do this, you should create a Drupal Distribution and release it on Drupal.org/project/distributions along with the 600 or so distributions already available there. Like all other Drupal projects, you use git to interact with the repository, and you also need to be a git-vetted user if you want to create a non-sandbox distribution.

You build a distribution by first exporting its features (including custom cck, templates and Views using the Features module. Then turn this into a distribution using the Profiler library to create an install profile.  Finally, you package the distribution with the Drush Make packager (part of Drush).


Creating a Rule condition that evaluates a field an entity that is referenced by a created node I'm trying to create a rule for new node content that is based on entity references.

To give some background I have story pages and chapter pages. The story pages are story meta data, the chapters are real content. The chapters reference the story pages and are sorted by chapter numbers set by the users.

I want to create a rule for when a new chapter is published. But it needs to be able to evaluate a field on the Story the chapter is a part of. How do I get rules to go to that story entity in question and check the value of the fields in question?

Okay, I think I figured out a way to pull this off, and even if it's not the best practice for what I'm attempting to do, it is working.

So like I said, I was trying to create a condition that relies on information contained in a node that is being referenced as an entity. One of the discussion posts indicated I may need to create a component.

So I went to components and created a new component. Data type I set for Any Entity then named it story page (story_page).

I set conditions that the entity is content, and then a condition where content is of type story page.

Now that we have the content type identified and set we create a condition for list contains item and search for the item in the specific taxonomy I'm looking for.

TO understand this component understand that there are some folk who post more mature content on my page that I DON'T want exposed to the general public. So I require that that kind of content be marked by a specific setting in two fields.

This checks one of those fields and makes the determination. The information however on a chapter for that to be determined is stored in a referenced node which is set in field_story. You have to be able to get the information from that node, and that information is stored in field_genre. So the Componenet is built like this.

{ "rules_check_for_erotica" : {
"LABEL" : "Check for Erotica",
"PLUGIN" : "and",
"OWNER" : "rules",
"TAGS" : [ "Entity Reference", "Node", "Twitter" ],
"REQUIRES" : [ "rules" ],
"USES VARIABLES" : { "story_page" : { "label" : "Story\u00a0Front Page", "type" : "entity" } },
"AND" : [
  { "entity_is_of_type" : { "entity" : [ "story-page" ], "type" : "node" } },
  { "node_is_of_type" : {
      "node" : [ "story-page" ],
      "type" : { "value" : { "story_front_page" : "story_front_page" } }
    }
  },
  { "list_contains" : { "list" : [ "story-page:field-genre" ], "item" : "161" } }
]

}
}

Now, we have a component that can test and figure out if the attached story field has that entry. We can then use it for rules related to story pages to test for it, and make a determination on what to do based on it.

I then created another rule similar to this but it was checking a different field to determine if the story in question is an original story  or if it's part of an original series on this page. I then created a new rule to check the chapter page.

{ "rules_publish_new_chapter_darkscribes_" : {
"LABEL" : "Publish New Chapter (Darkscribes)",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "Facebook", "Social", "Twitter" ],
"REQUIRES" : [ "rules", "twitter_actions", "fb_autopost_entity" ],
"ON" : { "node_insert--chapter_page" : { "bundle" : "chapter_page" } },
"IF" : [
  { "component_rules_check_for_original" : { "story_page" : [ "node:field-story" ] } },
  { "NOT component_rules_check_for_erotica" : { "story_page" : [ "node:field-story" ] } }
],
"DO" : [
  { "rules_core_twitter_actions_set_status_action" : {
      "message" : "[node:author] just posted a new chapter for [node:field_story] | Chapter [node:field-chapter-no-]: [node:title] | [node:url]",
      "sender" : "Darkscribes"
    }
  },
  { "entity_create" : {
      "USING" : {
        "type" : "facebook_publication",
        "param_type" : "post",
        "param_user" : [ "site:current-user" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-facebook-link" ],
      "value" : [ "node:url" ]
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-facebook-message" ],
      "value" : [ "node:body:summary" ]
    }
  },
  { "publish_to_facebook" : {
      "USING" : { "publication" : [ "entity-created" ], "pages" : "215544991848808" },
      "PROVIDE" : { "facebook_publication_id" : { "facebook_publication_id" : "Facebook publication returned ID" } }
    }
  },
  { "data_set" : {
      "data" : [ "facebook-publication-id" ],
      "value" : [ "facebook-publication-id" ]
    }
  },
  { "entity_save" : { "data" : [ "entity-created" ] } }
]

}
}

I tested it to see if it would post a message to one of the two twitter accounts in question, and it SEEMS to have done just right.

I may need to revisit this answer later and add an image or screenshot to it at some point. Or find a way to consolidate my content checking rules.


Unable to programmatically create user I am trying to programmatically create a user in Drupal 8 using the following code.

$language = \Drupal::languageManager()->getCurrentLanguage()->getId();

$user = \Drupal\user\Entity\User::create();
$user->setPassword($form_state->getValue('pass'));
$user->enforceIsNew();
$user->setEmail('test@test.com');
$user->setUsername('test_test');
$user->set("init", 'test@test.com');
$user->set("langcode", $language);
$user->set("preferred_langcode", $language);
$user->set("preferred_admin_langcode", $language);
$user->activate();
$user->save();

When I execute it, I get the following exceptions.

  Drupal\Core\Entity\EntityStorageException: Field type is unknown. in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 783 of  /home/printhouseheroes/public_html/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
  InvalidArgumentException: Field type is unknown. in Drupal\Core\Entity\ContentEntityBase->getTranslatedField() (line 586 of
  /home/printhouseheroes/public_html/core/lib/Drupal/Core/Entity/ContentEntityBase.php).

How can I avoid getting those exceptions?

The exceptions aren't caused from the code shown in the question. The second exception is caused from the following code in ContentEntityBase::getTranslatedField().

// Populate $this->fields to speed-up further look-ups and to keep track of
// fields objects, possibly holding changes to field values.
if (!isset($this->fields[$name][$langcode])) {
  $definition = $this->getFieldDefinition($name);
  if (!$definition) {
    throw new \InvalidArgumentException("Field $name is unknown."); // Line 586.
  }

  // Omissis.

}

There is a module that is trying to access the type field, which doesn't exist for the User entity.

Your code is correct. Eventually, instead of setting the user fields using a setter method, you could use the array User::create() accepts as first parameter, which uses the following array keys (among others):

name
mail
pass
status
roles (an array)
langcode
preferred_langcode
preferred_admin_langcode

There isn't an equivalent value for enforceIsNew(), so you need to call that method on the created user object.


drupal views : display previous nodes I am having difficulties to filter data with views. I have made several video lessons on a subject and managed to display on the side of each video all other related videos in a block.
However i wish to see displayed in this block all related AND Previous videos.

I created a field called "order" (integer) in my content type, and i wonder how i can add a filter to make sure that the related videos have an "order" value lower than the "order" value of the video being displayed.

I 'd be greateful if anybody could help me with that.

It would be best to create a page/block (basically just a different views display) to achieve that.

The constraints that you have i.e. Previous and Related can only find a practical application if your videos belong to the same category.

If I am getting the question right what you are better off doing is creating another block which displays all videos irrespective of the categories.


How to Implement Modal AJAX Form Pagination With the new Drupal8 Modal API I've been able to get a pretty powerful form going.

The form essentially does a POST to an API and displays some search results, which the user can filter. I want to paginate these results.

I'm having a lot of trouble wrapping my head around how this could be done, whether it's with custom ajax requests to increment some kind of counter that is used in the buildForm() function that does the API call, or something else. I've attempted to use Drupal's built in pagination but that doesn't seem like a feasible option as it doesn't even take route parameters.

A full example of the form can be seen at https://github.com/acbramley/embridge/blob/master/src/Form/EmbridgeSearchForm.php

Pagination seems to be broken in core through modals as well, when using a modal window to display (for example) the admin/content screen, pagination doesn't work.

To implement this I went down a similar route as the "Add another item" functionality on field api fields. For reference, this is done in WidgetBase.php.

Firstly, I copied over a couple of static functions to get and set values inside storage:

/**
 * {@inheritdoc}
 */
public static function getModalState(FormStateInterface $form_state) {
  return NestedArray::getValue($form_state->getStorage(), ['search_results']);
}

/**
 * {@inheritdoc}
 */
public static function setModalState(FormStateInterface $form_state, array $field_state) {
  NestedArray::setValue($form_state->getStorage(), ['search_results'], $field_state);
}

Then in buildForm() I added this to intialise the storage if it wasn't set yet.

if (!static::getModalState($form_state)) {
  $field_state = array(
    'page' => 1,
  );
  static::setModalState($form_state, $field_state);
}

And then use the storage to get the page parameter for my search:

$modal_state = static::getModalState($form_state);
$page = $modal_state['page'];
$search_response = $this->getSearchResults($page);

The crucial part of the implementation was separating the increment in the page variable from the ajax handler and putting it into the submit handler. So for the "Next" button:

// Add "next page" pager.
$form['next'] = [
  '#type' => 'submit',
  '#value' => $this->t('Next'),
  '#submit' => ['::nextPageSubmit'],
  '#ajax' => array(
    'callback' => '::searchAjax',
    'wrapper' => self::AJAX_WRAPPER_ID,
    'effect' => 'fade',
  ),
];

And the submit handler

/**
 * Submission handler for the "Next page" button.
 *
 * @param array $form
 *   The form.
 * @param FormStateInterface $form_state
 *   The form state.
 */
public function nextPageSubmit(array $form, FormStateInterface $form_state) {
  // Increment the page count.
  $modal_state = self::getModalState($form_state);
  $modal_state['page']++;
  self::setModalState($form_state, $modal_state);

  $form_state->setRebuild();
}

My ajax callback is then the same for searching, and paginating.

I also added a submit handler to the search button to reset the page back to 1.

The full source code for the form in this state can be found at https://github.com/acbramley/embridge/blob/2a561c9c388ccf715f93727cf136e50fc02163c9/src/Form/EmbridgeSearchForm.php

These code snippets are essentially the guts of what I needed to get the pagination working.


How can I use field_attach_load() Possible Duplicate:
  Listing entity fields

I want list fields of my content type(example: blog), so as described at Drupal API reference, I should pass $entity_type and $entities to this function.

I know $entity_type is 'node', but how can I fill $entities?
I should fill $entities with bundle of "blog" so I should know the bundle ID.
How can I know bundle ID for blog?

If you want the list of fields per content type (now bundles in Drupal 7), you should use field_info_instances().

//List all fields of bundle "your_content_type" using devel module
dsm(field_info_instances('node', 'your_content_type'));


Drupal autocomplete form, multiple values I have created custom module to add user awards. This award = some text(like Php developer of the month) and image, and i need to implement feature, which can add this award to multiple users in this form
This is my form:

function user_awards_admin_settings() {
    $form = array();
    $form['award_description'] = array(
        '#type' => 'textfield',
        '#title' => 'award description',
    );

    $form['name'] = array(
        '#type' => 'textfield',
        '#title' => t('Assign to'),
        '#autocomplete_path' => 'user_awards/autocomplete',
    );
    $form['user_awards_block_image'] = array(
        '#type' => 'managed_file',
        '#name' => 'user_awards_block_image',
        '#title' => t('Block image'),
        '#size' => 40,
        '#description' => t("Image should be less than 400 pixels wide"),
        '#upload_location' => 'public://'
    );

    $form['#submit'][] = 'user_awards_settings_submit';
    return system_settings_form($form);
}

And this is my autocomplete function:

function user_awards_autocomplete($string) {
    $matches = array();
    $return = db_query("SELECT name FROM users where lower(name) like '" . $string . "%' LIMIT 10");
    // add matches to $matches
    foreach ($return as $row) {
        $matches[$row->name] = check_plain($row->name);
    }
    // return for JS
    drupal_json_output($matches);
}

And submit one:

function user_awards_settings_submit($form, $form_state) {
    $file = '';
    if (isset($form_state['values']['user_awards_block_image'])) {
        $file = file_load($form_state['values']['user_awards_block_image']);

        $file->status = FILE_STATUS_PERMANENT;

        file_save($file);
    }
    $description = $form_state['input']['award_description'];
    $name = $form_state['input']['name'];
    db_query('INSERT INTO {user_awards} (name, award_description, fid) VALUES (:name, :award_description, :fid)', array(
        ':name' => $name,
        ':award_description' => $description,
        ':fid' => $file->fid,
    ));
    drupal_set_message('form has been submitted');

}

I need somehow to make $form['name'] to be multiple(autocomplete) textfield, comma separated or so, how can i do it?
At this moment its only autocomplete first value of NAME field

Add a select list to your form. Add some #ajax to your textfield. Every time the textfield changes content, add the value (via #ajax) to your select list. Use the values of your select list in the submit callback.

OR

You could to it by attaching a custom JavaScript file using $form['#attached']['js'] with some good old JavaScript to fetch the users and add them to the csv textfield (autocomplete). Then split the values in the submit and add them to the database.

OR

Just use a select if that's OK with you.


How do I change my navbar from "left to right" to "right to left"? I built an English language web site, and now I'm working on the Arabic version.

How do I change the navigation bar to be displayed right to left?
I'm using the Bootstrap theme 3.3.5.

Note: Following answer is for D7, but the concept is same for D8 also I think, if you want to do using CSS, Just you need to apply the same logic where to apply CSS float: left; and float: right;.

This you can do with CSS.

If there is just a menu with list of items, you can do easily with float: right at appropriate place.

But, bootstrap's default nav-bar contains Logo Site name primary-menu and Secondary-menu, Hence css will be some complicated.

Now, I have used the following set (LTR Default),

And after looking their HTML I have applied following CSS,

.navbar {
    .navbar-header {float: right;
        a.logo { float: right !important;}
    }
    .navbar-collapse{
        nav {

            ul.menu.navbar-nav {float: right;
                li {
                    float: right;
                }
            }
            ul.menu.navbar-nav.secondary {float: left !important;
                li {
                    float: right;
                }
            }

        }
    }
}

After applying the CSS, It has arranged in such a way.

If you slightly practice, you can by yourself come to know how it works, it is easy.


How do I check a custom field has a value? I'm using the "Entity is of type" condition for the After updating content event, the rule only fire when the field has a value of that updated/created node. The field, which is part of a custom content type.

When I select Entity is of type and try to add Entity(Specifies the entity for which to evaluate the condition.) value like [node] and Type(The entity type specified by the condition.) of value like [node:field_alias_1:value]

I got the following error.

  TypeError: Argument 1 passed to Drupal\rules\Plugin\Condition\EntityHasField::doEvaluate() must implement interface Drupal\Core\Entity\FieldableEntityInterface

If the field has the value of that content type, how do I create a new redirect alias using that field name?

To my knowledge the current answer to this question is: you can't do that yet with the most recent D8 version of Rules. Refer to #d8rules status update November 2017 to get a better understanding of the current status of Rules for D8. Here is a quote from it:

  ... Fago can’t dedicate time required to develop the module further. What Rules is really missing at the moment is development capacity to help finish the last milestone.

One never realizes what has been done, only what remains to be done ... So start here if you wonder how to contribute.


Webform multi-page submit handler fires on every page I have created a couple of webform submit handlers before, but my new one fires on every page submit rather than when the last page is submitted.

How do I get the webform handler to only fire after the full form is submitted?

Below is what I have at the moment, which fires on each page:

namespace Drupal\the_api\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Webform submission remote post handler.
 *
 * @WebformHandler(
 *   id = "membership_api_post",
 *   label = @Translation("New Membership to API"),
 *   category = @Translation("External"),
 *   description = @Translation("Posts a new membership through to the API."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */
class NewMembershipWebformHandler extends WebformHandlerBase {

  /**
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @param \Drupal\webform\WebformSubmissionInterface $webform_submission
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    parent::submitForm($form, $form_state, $webform_submission);

    kint($form_state);

  }
}

You can use $webform_submission->getState() to determine if the submission is completed. The EmailWebformHandler includes decent examples on how to the submission state. I recommend trying to use WebformHandler::postSave() instead of WebformHandler::formSubmit().


how to use css sprite in all my pages ( menu+ views) i have a page contain view and menu and i want to use same icon  for both,
so i made a sprite image but i don't know how to use it in 2 different classes?

Any help with this would be much appreciated.

Cheers in advance.

You can use same image in different classes already; i am not sure that i understood your problem(I was going to ask for details but my reputation is not enough to add comments yet; so i am adding answer.).

.class-one {
  background: url("/your/path/to/images/your-sprite-image.png") no-repeat 0 0;
  ...
}

.class-two {
  background: url("/your/path/to/images/your-sprite-image.png") no-repeat 0 0;
  ...
}

If you need to change image's position, you can change first 0 for left, second 0 for top position.

If they are the same; you can merge them:

.class-one, .class-two {
  background: url("/your/path/to/images/your-sprite-image.png") no-repeat 0 0;
  ...
}


Escaping CSS digits, 0 is removed from CSS aggregated files The following HTML markup won't work on a production site.

TEXT

This is the code in the custom.css file.
.iconleft.\31 09,
.iconleft.\31 12,
.iconleft.\31 10,
.iconleft.\31 11,
.iconleft.\31 20 {
  background: #B0CD00;
}

.iconleft.\31 09 works on localhost with xampp and no aggregation. On the production site, where Advanced CSS/JS Aggregation is activated, it wont work for 109.
In the aggregated CSS file, I see .iconleft.\31 9 as CSS class. It seems that 0 has been removed.
Do you have any hint?

I think the code is valid.
Anyway due to lack of time i decided to ad an "id" to the class. So the html is now

Text

And the css
.iconleft.id-109,
.iconleft.id-112,
.iconleft.id-110,
.iconleft.id-111,
.iconleft.id-120 {
  background: #B0CD00;
}

This is working for me.
But if somebody knows why aggregation removes the "0" please let me know.


Localization vs Translation from a Drupal perspective Been wondering what is the difference between the meaning of these two words when it comes to Drupal, and it seems they are used interchangeably. Is that a correct understanding?

In Drupal, the terms "localize" and "translate" have special meaning (beyond the typical Internationalization/Localization meanings).

"translate" - this typically means that you end up with a "translation set" of objects. For example, an English source node with its German & French translated nodes (3 related objects). Or, a French source taxonomy term and its Spanish translated term (2 related objects).

"localize" - this typically means that you only have one "object" but can translate the textual information related to the object via string translation. For example, for a menu item, you have one English menu item but then translate the title of the menu item into Spanish (while both languages have the same link).

I've sorted this all out because I'm writing a book on Drupal 7 multilingual sites for Packt that will be out very soon: http://www.packtpub.com/drupal-7-multilingual-sites/book


Migration from CSV: how to define a default value for autoincremental id field? I run migrations from CSV using Migrate Source CSV, Migrate Plus and Migrate Tools modules and it works fine.
The result of one of these migration is a custom entity which key is a 'id' field that has the 'AUTO_INCREMENT' property in the database.
Here is my migration_contractssubscriptions.yaml

id: migration_contractssubscriptions
migration_group: null
label: 'Contract Subscriptions migration from CSV'
source:
  plugin: csv
  path: /mypathto/migration_ContractsSubscriptions.csv
  delimiter: ';'
  enclosure: '"'
  header_row_count: 1
  keys:
    - id
process:
  id: id
  contract_id: contract_id
  member_id: member_id
  sharedwith_member_id: sharedwith_member_id
  comment: comment
  quantity01: quantity01
  quantity02: quantity02
  quantity03: quantity03
  quantity04: quantity04
  owner_id:
    plugin: default_value
    default_value: 1
destination:
  plugin: 'entity:contract_subscription'

I'd like to get rid of 'id' in my csv file and let the migration process handle the value of the resulting id.
I tried to remove keys: - id and id: id but I get an error...
How can I achieve that?

I finally understood that keys in source is the way to make each row of the csv file unique. It may be anything.
So I changed to:

  keys:
    - contract_id
    - member_id

I removed id: idfrom processand it works!
The value of id field in the database is properly auto-incremented.


HybridAuth: How to bypass 'allow access' button I have installed HybridAuth module to login in LinkedIn.  The following is the url through which user can log in from Popop window.

  http://www.mydrupal.com/hybridauth/window/LinkedIn?destination=node/38&destination_error=node/13

The logged in window gives 'allow access' button each time when open a popup.

Question:  How to bypass this 'allow access' button after the first attempt? I have already gone through various links but could not get proper idea.

Screen shot is as follows.

I am also face the same problem, But am using ulgoin module. After login You must first authorize LinkedIn integration to use related features.

In this button available in user edit page. Once you have synchronized your details , in the above message not appear in the second attempt.

Thanks


Cache breaks functionality? I have added some jQuery functionality to create a popup when hovering over a link to the script.js file included with the particular theme I am using. It is enclosed in jQuery(document).ready(function($) {}.

It works perfectly at first, but it seems that once Drupal 7 caches/aggregates the script.js file, it no longer works at all. I'm not 100% sure it is a caching related issue, as it works fine for hours, but eventually stops working. Clearing the CSS/JS cache after it stops working makes it work again.

function contactLinkInit() {
        var div = '
' +
                '10320 Globe Road
Morrisville, NC 27560
' +
                'Phone: 919-361-4333
' +
                'Fax: 919-361-4388
' +
                'info@dosoffice.com';

        var firstRun = true;
        var firstEntered = true;
        var enteredPopup = false;

        $("a.contact-link").mouseover(function(event) {
            if (firstRun) {
                $("body").append(div);

                $("div.contact-popup").mouseover(function() {
                    if (!firstEntered) {
                        enteredPopup = true;
                    }
                    else {
                        firstEntered = false;
                    }

                    $("div.contact-popup").css('visibility','visible');
                });

                $("div.contact-popup").mouseout(function() {
                    enteredPopup = false;
                    $("div.contact-popup").css('visibility','hidden');
                });

                $("a.contact-link").mouseout(function() {
                    if (!enteredPopup) {
                        $("div.contact-popup").css('visibility','hidden');
                    }
                });
                firstRun = false;
            }
            $('div.contact-popup').css('left',event.pageX + "px");      // <<< use pageX and pageY
            $('div.contact-popup').css('top',event.pageY + "px");
            $("div.contact-popup").css('visibility','visible');
        });
    }

    contactLinkInit();

I'm sure what I've done here is not best practice, neither Javascript nor Drupal are my forte. Not only am I looking for a solution to the problem itself, I certainly wouldn't mind suggestions as how to improve the code itself.

I have redone my code as suggested in the comments so that it uses Drupal behaviors and the Drupal's javascript-api. I also moved my code out of the existing theme's script.js to its own file, and added that file to the scripts array in the theme's .info file.

Below is my updated code, in case it should help anyone that encounters this same sort of problem and is unfamiliar with Drupal behaviors. This has solved my problem with my code no longer working once the JS is aggregated and/or cached.

   (function($) {
     Drupal.behaviors.contactLinkHoverPopout = {
         attach: function(context, settings) {
             var div = '
' +
                 '10320 Globe Road
Morrisville, NC 27560
' +
                 'Phone: 919-361-4333
' +
                 'Fax: 919-361-4388
' +
                 'info@dosoffice.com';

             var popupVisible = false;

             // we only want mouseovers applied once!
             $('a.contact-link', context).once(function() {
                 // add the invisible popup div
                 $('body', context).append(div);

                 // add mouseover to contact-link
                 $('a.contact-link', context).mouseover(function() {
                     $('div.contact-popup', context).css('left', event.pageX + "px");
                     $('div.contact-popup', context).css('top', event.pageY + "px");
                     $('div.contact-popup', context).css('visibility', 'visible');
                     popupVisible = true;
                 });

                 $('div.contact-popup', context).mouseover(function() {
                     $('div.contact-popup', context).css('visibility', 'visible');
                     popupVisible = true;
                 });

                 $('a.contact-link', context).mouseout(function() {
                     if (popupVisible) {
                         $('div.contact-popup', context).css('visibility', 'hidden');
                         popupVisible = false;
                     }
                 });

                 $('div.contact-popup', context).mouseout(function() {
                     if (popupVisible) {
                         $('div.contact-popup', context).css('visibility', 'hidden');
                         popupVisible = false;
                     }
                 });
             });
         }
     };
 }(jQuery));


Entity queue JSONAPI pagination & How to add JSON API in views? I'm using below modules

https://www.drupal.org/project/entityqueue & JSON API

Through entity queue. I have added 5 Articles.

Now I would like to apply pagination on that.

We are accessing via

http://domain.com/jsonapi/my-5-articles?include=items

I tried to add include=items&items[paging]=1. but seems not working

I need to add limit & offset

If we do same in

http://domain.com/jsonapi/node/article?page[limit]=1

then we are getting

"links": {
"self": "http://domain.com/jsonapi/node/article?page%5Blimit%5D=1",
"next": "http://domain.com/jsonapi/node/article?page%5Boffset%5D=1&page%5Blimit%5D=1",
"last": "http://domain.com/jsonapi/node/article?page%5Boffset%5D=31&page%5Blimit%5D=1"
},

We are not able to get same in entityqueue.

How to add JSON API in views?

Is sounds like you're assuming functionality that may-or-may-not be there.
Assuming /jsonapi/my-5-articles is an alias for /jsonapi/entity_subqueue/$MY_QUEUE_MACHINE_NAME?include=items, items[paging] isn't a query param for pagination, only page is (with [] options for specifying page size & offsets).
It sounds like what you want, in terms of the JSON API spec, is a paginated compound document (i.e. the included property that has all your queue nodes for the items relationship). Per the JSON API spec:

A server MAY choose to limit the number of resources returned in a response to a subset (“page”) of the whole set available.
A server MAY provide links to traverse a paginated data set (“pagination links”).
Pagination links MUST appear in the links object that corresponds to a collection. To paginate the primary data, supply pagination links in the top-level links object. To paginate an included collection returned in a compound document, supply pagination links in the corresponding links object.

It's optional for the JSON API module to supply pagination links. If it does supply them, it will be in the links document property for the resource you're requesting.
Since you're wanting pagination for included resources, the spec says:

To paginate an included collection returned in a compound document, supply pagination links in the corresponding links object.

I'm assuming "corresponding links object" is different from "top-level links" and they're referring to links property for objects within the included array.
From a quick look over the JSON API docs/code it doesn't appear to support this functionality. That may or may not be the case, you'll need to see if it does. You should check the project's issue queue.
The specs' flexibility on this scenario means the authors may not have put the functionality in there. If that's the case, you'll need to figure out a workaround or implement your own solution here.


Where does theme($row) get evaluated? I am baffled by this line of code:

$work[$id] = $view->field[$id]->theme($row);

Does anyone know where theme($row) gets evaluated?

$word[$id] gets set to this emfield's url, "http://mysite.com/myvideo.flv", which is the value of both:

$view->field[$id]->last_render
$view->field[$id]->original_value

So I am guessing that theme($row) gets evaluated to either 'last_render' or 'original_value'.
But when I add debug code to print theme($row), nothing gets printed.

Any ideas?

Here is the context in which this line of code appears, from views-view-swftools.tpl.php:

   foreach ($rows as $key => $row) {

          // Reset the work array
          $work = array();

          // Render each field in this row using the assigned handler
          foreach ($keys as $id) {
            $work[$id] = $view->field[$id]->theme($row);
          }
          ...
    }

This is a method call, the theme method is invoked on the $view->field[$id] object. The method is likely views_handler_field::theme but it may have been overrided by the  views_handler_field subclass used for a particular field handler. Usually, the method will eventually ends up calling the theme() function to use a defined theme function or template for the field (if this is a CCK field, a formatter will likely be used).


Apache Solr & Boost module conflict? I'm running Drupal 7, Apache Solr module 1.2, Boost 1.3

When performing a search as an anonymous user, I (most of the time) just get redirected to the front page.
I suspect some conflict with the boost module as this only happens for anonymous users and removing the .htaccess rules for boost seems to fix the problem. Although the eratic behaviour is quite confusing.

I notice that the form submit action for the search is always "/"
In the access logs, I see that the normal flow is:
- POST on "/"
- 302 Redirect on node/search/...

When having the problem as anonymous user, the flow is:
- POST  on "/"
- 200 Status code and the boost cached index page is returned. No 302

Here are my boost .htaccess directives:

  # Allow for alt paths to be set via htaccess rules; allows for cached variants (future mobile support)
  RewriteRule .* - [E=boostpath:normal]

# Caching for anonymous users
# Skip boost IF not get request OR uri has wrong dir OR cookie is set OR request came from this server OR https request
RewriteCond %{REQUEST_METHOD} !^(GET|HEAD)$ [OR]
RewriteCond %{REQUEST_URI} (^/(admin|cache|misc|modules|sites|system|openid|themes|node/add|comment/reply))|(/(edit|user|user/(login|password|register))$) [OR]
RewriteCond %{HTTPS} on [OR]
RewriteCond %{HTTP_COOKIE} DRUPAL_UID [OR]
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [S=4]

##Added as the front page was displaying the content of index.php instead of cached html
RewriteCond %{REQUEST_URI} ^\/index.php$
RewriteCond cache/normal/drupaltestsite.com/_\.html -s
RewriteRule .* cache/normal/drupaltestsite.com/_\.html [L,T=text/html]

# GZIP
RewriteCond %{HTTP:Accept-encoding} !gzip
RewriteRule .* - [S=1]
RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html -s
RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html [L,T=text/html,E=no-gzip:1]

# NORMAL
RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html -s
RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html [L,T=text/html]

As the action is a POST, none of these directives should be executed I think, so I am not sure where the problem is.
Where is the 302 redirect made to forward the request on search/node... ?

Any help appreciated.
Jerome

Add your search paths to list of pathes boost ignores, either via UI or in the line

RewriteCond %{REQUEST_URI} (^/(admin|cache|misc|modules|sites|system|openid|themes|node/add|comment/reply))|(/(edit|user|user/(login|password|register))$) [OR]

Boost should always be skipped for dynamically generated pages, it can't handle it to well.


how to reorganize with twig a form builded in a custom module and keep working ajax callback? I've a form created programatically with a few fieldset and some inputs in these use ajax callback. The structure is like this :

$form['global']['controls'] = [
  '#type' => 'fieldset'
];

$form['global']['info'] = [
  '#type' => 'fieldset'
];

$form['global']['description'] = [
  '#type' => 'fieldset'
];

I've defined a theme template in my .module file and created the twig template. This is the twig template :

  {{ form.global.info }}
  {{ form.global.controls }}
  {{ form.global.description }}

The form display correctly but ajax callback don't work : the callback are executed but don't change the elements.

All callbacks work with this :

  {{ form }}

But I can't rearange the form with this twig code.

What I want is the possibility to rearange the order of the fieldsets in twig : put the fieldset 'description' before 'info', or 'controls' before 'info', etc. And keep ajax callbacks working.

Is it possible? And how?

The solution for this case was just to add {{ form|without('global') }} at the end of the .twig file, like this :

<div>
  {{ form.global.info }}
  {{ form.global.controls }}
  {{ form.global.description }}
</div>
{{ form|without('global') }}


Convert seconds to time format I have 10396080 seconds, and I want it to look like this: xxx hours, xxx minutes.
Is there some function for that?

I have 10396080 seconds, and I want it to look like this: xxx hours, xxx minutes. Is there some function for that?

Not really.  What you want is 10396080 seconds converted to 2887 hours 48 minutes, and I know of now existing function that does that.

There  is format_interval().

 $seconds = 10396080;
 $string = format_interval($seconds, 2);
 echo $string;

But that will output "4 months 7 hours".

However, the following custom function:

 function _hoursminutes($interval, $granularity = 2, $langcode = NULL) {
   $units = array(
    '1 hour|@count hours' => 3600,
    '1 minute|@count minutes' => 60,
    '1 seconds|@count seconds' => 1,
  );  $output = '';
  foreach ($units as $key => $value) {
    $key = explode('|', $key);
    if ($interval >= $value) {
      $output .= ($output ? ' ' : '') .
        format_plural(floor($interval / $value), $key[0], $key[1], array(),
        array('langcode' => $langcode));
      $interval %= $value;
      $granularity--;
    }
    if ($granularity == 0) {
      break;
    }
  }
  return $output ? $output : t('0 second', array(), array('langcode' => $langcode));
}

 $seconds = 10396080;
 $string = _hoursminutes($seconds, 2);
 echo $string;

This will output: "2887 hours 48 minutes", which presumably what you want.


How to programatically add a pseudo field to views and display the field value based on value of other field? I need to add a field to view and display the value of that field depending on the value of other fields already present.

The pseudo field i need to add is not connected with any database table.

In addition to the preprocess hook approach noted in the comments, you may want to use:

Computed Field Module https://www.drupal.org/project/computed_field
Views PHP Module https://www.drupal.org/project/views_php


Core JavaScript is not included in all pages I'm developing a theme in Drupal 8. This is my theme.libraries.yml file:

default:
 version: 1.x
 css:
  theme:
   css/bootstrap.css: {}
   css/style.css: {}
   css/font-awesome.min.css: {}
   css/animate.min.css: {}
 js:
    js/galip.js: {}

When I try to view the source of the front page page, I see the JavaScript files like ready.min.js. jquery.min.js, jquery.once.min.js which I don't see in the login page and other pages.

Why is this happening? How do I include the core JavaScript files in all pages?

Drupal 8 adds little to no javascript by default, and thankfully doesn't force jQuery on us any more :)

You need to declare your dependencies explicitly:

default:
 version: 1.x
 css:
  theme:
   css/bootstrap.css: {}
   css/style.css: {}
   css/font-awesome.min.css: {}
   css/animate.min.css: {}
 js:
    js/galip.js: {}
 dependencies:
    - core/jquery
    - core/jquery.once
    - etc...


List members visable in any organic group I am working on a Drupal 7 & OG & Views site, and I am trying to write a view that shows what users another user can 'see' through any group he's a member of.

ie:
User A - Member of Group A, Group AB, Group AC
User B - Member of Group B, Group AB
User C - Member of Group C, Group AC

Output of View for ..
User A - User A, B, C
User B - User A, B
User C - User A, C

Thanks..

Go to OG Members > EDIT > CONTEXTUAL FILTERS > PROVIDE DEFAULT VALUES > CURRENT OG GROUP FROM CONTEXT ....i assumed u have the OG MEMBERS which is a default view created after installation of the latest module.


I have a script that need to place after closing tag after of body? I have JS script . I need place this script after closing tag of body using php.
How can i place that script.

Adding a <script> tag (or any tag except a comment) outside <head> or <body> is invalid HTML. Drupal doesn't want to help you to produce invalid HTML, so it contains nothing that would help you to do this.

I would examine your motivation for doing this, and reconsider whether you want to produce a valid or invalid document. If you really want to go down the invalid route, then you may as well just edit your theme's html.tpl.php file and stick the script at the bottom, as you won't find any API methods that can be used to do it for you.

FYI, IE10+ will ignore the script altogether, Chrome and FF will honour it for now, but may not in the future, other browsers/versions will probably do various other things.


Render View in twig template I'm pretty new to Drupal, and very new to Drupal 8.  I've created a view, and have set up it up with a display block.  I'm trying to render this on a specific page.  So, I created a page template and a preprocess hook, created the following function.

function MYTHEMENAME_preprocess_node__13(&$variables) {
 $block = \Drupal\block\Entity\Block::load('views_block__downloads_block_2');
 $block_content = \Drupal::entityManager()->getViewBuilder('block')->view($block);
 $variables['downloads'] = $block_content;
}

When I place {{ downloads }} in my page template (page--node--13.html.twig) nothing happens.

Any ideas what I might be doing incorrectly?

When you configure the visibility of the block in UI you can use a standard region and the standard page template.

If you want to do this with a specific page template similar to the question, add a region download to the theme, place the view block in this region and render the region in the page template specific to the node page--node--13.html.twig:

{{ page.download }}


Move people search to list page Is there a way or module that allows me to move the search tab of the People page to the List tab?

https://www.drupal.org/project/admin_views makes the users and content page a lot friendlier. On of the things it does is putting a search field on the users page.

One of the modules I use on every project.


how to correctly chain multiple files in '$settings['container_yamls'][]'? In the settings.php file, I have the following line, to use a local service.yml.

$settings['container_yamls'][] = __DIR__ . '/services.yml';

I need to install the Redis module, which instructs to put the following line in the settings.php file.

$settings['container_yamls'][] = 'modules/redis/example.services.yml';

I'm not sure how the settings array works. I think that just adding that statement will overwrite the existing one.

I want to add the array item as suggested in the documentation for that module.

Should I use these lines?

$settings['container_yamls'][] = __DIR__ . '/services.yml';
$settings['container_yamls'][] = 'modules/redis/example.services.yml';

Or should I use these lines?

$settings['container_yamls'] = array(
  __DIR__ . '/services.yml',
  'modules/redis/example.services.yml',
);

The settings.php file already contains the following line.

$settings['container_yamls'][] = __DIR__ . '/services.yml';

It is much easier to add the following one at the bottom of the settings.php file.

$settings['container_yamls'][] = 'modules/redis/example.services.yml';

Since it is added on the bottom of the file, it is easier to find and remove it, in the case you decide not to use that module anymore. In this case, you just remove a single line, and Drupal doesn't use that module's services anymore.

Also, if you install another module that requires to add a similar line, you just need to add a $settings['container_yamls'][] which can be easily removed without touching the other lines.

Those are the only considerations I could make about which code snippet I would use. Otherwise, for PHP 5.5 (and Drupal), the following code snippets are perfectly equivalent.

$settings['container_yamls'][] = __DIR__ . '/services.yml';
$settings['container_yamls'][] = 'modules/redis/example.services.yml';

$settings['container_yamls'] = array(
  __DIR__ . '/services.yml',
  'modules/redis/example.services.yml',
);

$settings['container_yamls'] = [
  __DIR__ . '/services.yml',
  'modules/redis/example.services.yml',
];


How do you get template preprocess functions to fire on hook theme suggestions? If you have a theme function like theme_field() for instance. I know you can do something like this:

function THEMENAME_preprocess_field(&$varialbes) {
  dpm($variables);
}

and that will print out the all the variables (if you have Devel enabled). Then I see theme_hook_suggestions like this "field__field_date__featured_event". However, when I try to do this:

function THEMENAME_preprocess_field__field_date__featured_event(&$varialbes) {
  dpm($variables);
}

The above does not work at all. Why is this? Is it possible to use a preprocess function on a theme suggestion? or are theme suggestions just for theme overrides and not for preprocessing?

thanks!

You need to do this before you can do that...

/*
 * Implements hook_preprocess_field().
 */
function YOURTHEME_preprocess_field(&$vars) {
    if ($vars['SOME_FIELD']) {
        $function = 'YOURTHEME_preprocess_field__'.$vars['SOME_FIELD'];
        if (function_exists($function)) {
            $function($vars);
        }
    }
}


Product Attributes Commerce I am moving my site from Ubercart to Commerce. I currently have some products set up with attributes that can be selected by a customer, please see this URL for an example http://www.wild-sage.co.uk/products/soap-box

How would I go about setting this up using Commerce?

Instead of dropdowns, you could use checkboxes and line item fields using Commerce custom products module.

All fields are supported as customer-facing line item fields, except some entity reference fields that use views to display their options. Note, the only limitation here would be that your fields would need to be able to react to the specific product.

Customizable products are like content types and define fields per bundle. So you would need a bundle per unique set of requirements. There is no limit, but it would probably be easier to model the "selection criteria" using fields on the products and then create a hook_form_alter() that would change the options available to select.

UPDATE: Code Example

Assumption 1: You've created a custom line item bundle

Assumption 2: You've created two fields. The first for the line item options (this would include all possibilities) and the second would be for the product (this would include any possibilities that match what that kind of product should have, doesn't need to be a complete list, but it would need to be the same ids/values of the first field).

Assumption 3: The workflow would look like this:

  select the soaps you would want to show PER product

Now, on the product display you would see this:

<?php
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0) {
    $product = $form_state['default_product'];
    $show_these = $product->field_include_these_soaps['und'];
    $all_soap_options = $form['line_item_fields']['field_soaps']['und']['#options'];
    $only_show = array();
    foreach ($show_these as $key => $value) {
      $real_key = $value['value'];
      $only_show[$real_key] = $all_soap_options[$real_key];
    }
    $form['line_item_fields']['field_soaps']['und']['#options'] = $only_show;
  }
}
?>


Is there a reliable autosave function for nodes? We're working with dirty forms to at least warn users before they leave an unfinished page before they save. It kind of works.  Would enabling revisions control work? At least in that case an admin could recover the last version.  Is there an automatic autosave ... say every 30 sections -- to be sure work is properly saved even if the user forgets to hit save?

Autosave

  The Autosave module automatically saves a snapshot of your content
  type form using AJAX. If the user's browser or machine dies while
  editing a node; the edits will be presented to the user the next time
  they return to the node. The user may toggle back and forth between
  the last saved version and the version with the edits that were lost
  and select which of these they would like to continue with.

  How often a form is autosaved as well as which content types to enable
  autosave for are admin configurable.


media_gallery images are not opening with proper size I have set up a media_gallery with colorbox in http://www.mountvilleresorts.com/. The gallery is working fine, but gallery images are shown very small.

After opening the images again, they are shown in the right size.

What is wrong with galleries that shows the images with a wrong size?

For the images to be of same size on every refreshing of page:-

you need to define the image style as per your requirement by Configuration > Media: Image Styles
Add the new style by giving it a name
Add the effect you want to give
Click on Add button and add the corresponding properties.
Update the style
Finally when uploading the images,choose the image style for the image ,this would result in the constant size of the image throughout instead of the variable size of the image.


How to migrate content of one content type to another content type I have two content types. Content type A and Content type B

I have some nodes of content type A and want to migrate them to content type B but the content of type A should remains in the system.

I have tried the node_convert module but it simply changes the node type of the existing content as the node ids remains the same.

Is there any other module or some hint to move into a custom solution?

You can use Feeds module or Migrate module. First you export the Type A into a CSV for example, then build an importer that imports data into the Type B and use the exported CSV file.

Be careful you choose the correct bundle for the importer (Type B) and to create new nodes. Check that your Unique field really is unique.


Using db_query and joins I am using Drupal 6 and trying to use db_query to delete rows from a table based on joins in order to untag a certain node of all tags of certain vocabulary.

This http://drupal.org/node/1079620 implies that delete doesn't work when using joins.

So I have a tried all the following forms of $queries:

1) $query = "DELETE a FROM {term_node} a LEFT JOIN {term_data} b ON a.tid = b.tid WHERE a.nid = %d AND b.vid = %d";

2) $query = "DELETE a FROM {term_node} a, {term_data} b WHERE a.tid = b.tid AND a.nid = %d AND b.vid = %d";

3) $query = "DELETE FROM a USING {term_node} AS a, {term_data} AS b WHERE (a.tid = b.tid) AND a.nid = %d AND b.vid = %d";

Before running

$result = db_query($query, $nid, $vid);

None of them deletes the rows from database. I have checked that $nid and $vid get the appropriate values and when I take of the curly brackets and run the query in phpMyAdmin it works like a charm.

I tried to perform simple query where there are no needs from joins. It didn't work either. But once again it works perfectly if I run the query in phpMyAdmin.

I started thinking could it be somehow related to the Drupal batch processing. The delete query not working gets executed when feeds module is performing a batch process (importing nodes to Drupal). So does Drupal during batch process somehow restrict access to tables or something? I didn't find anything in the mysql logs.

Some thing you can try doing is try printing the entire query string like,

$query = "DELETE a FROM {term_node} a LEFT JOIN {term_data} b ON a.tid = b.tid WHERE a.nid = ".$nid." AND b.vid = ".$vid;
print $query; //printing the query

Notice that I have used the variables instead of place holders %d. This might not be relevant but has helped me many times while debugging queries.

On the link you mentioned http://drupal.org/node/1079620, have you tried #5 ? if not give that a try, it should work IMO.


Adding Comments to Custom Node Template File Is there a way to add comments/comment form to a custom template file without having to install the Panels module? I had initially thought I could do it through a php script on the page, but have yet to find an answer.

I'm stuck, but all I need is for it to be at the bottom of my custom template file, which is for a custom content type. Thanks!

You may want to take the sample node template file and update as per your requirement. Here is the code which renders the comments section of the node template file.

<?php print render($content['comments']); ?>


How to use TrustedRedirectResponse()? I have used the following code on submit of a form to first send the form contents via guzzle and then redirect the form.  I get the error

Error: Call to undefined function TrustedRedirectResponse()

this is my code:

use Drupal\Core\Routing\TrustedRedirectResponse;

function mymodule_submit(&$form, FormStateInterface $form_state){
$url="xyz.com";
$post_data=array("color"=>"red");

$client = \Drupal::httpClient();
  $response = $client->request('POST', $url, [
    'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
     'verify'=>false,
    'form_params' => $post_data,

     ]);
    $status = $response->getStatusCode();

    $response = TrustedRedirectResponse(Url::fromUri($url));
    $form_state->setResponse($response);
}

I have two questions - how can I avoid the error , and is the order of getting the guzzle response and then getting the redirect response the correct order?

Your order seems correct, you need to instanciate a new TrustedRedirectResponse object like:

$response = new TrustedRedirectResponse($url_string);


how to add a "add user" tab to admin/people Currently on the user administration page admin/people there is a link below the tab row that lets admins add users (links to admin/people/create). Instead I would like to place that link in an additional tab next to the tabs "list" and "permissions". Has anybody experience in this? Or is there even a module for this?

I currently have difficulties finding anything because "add user tab" are quite generic search terms and there is a lot to find – but not meeting my problem.

thank you!

I think what you're asking is the same as this.  Apologies if not.

Here I've added a menu item that links out to another page.  So you should be able to change the links to your needs.  For this I created a module 'taskmenuextras'

    **
* Implementation of hook_menu_alter
*/
function taskmenuextras_menu_alter(&$items) {
    $items['user/%user/featuredjobs'] = array(
        'title' => t('Featured Jobs'),
        'page callback' => 'taskmenuextras_redirect_nodequeue',
        'access callback' => 'taskmenuextras_user_has_role',
        'access arguments' => array(1, array('admin')),
        'type' => MENU_LOCAL_TASK,
        'weight'  => 0,
        );

    return $items;
}

function taskmenuextras_redirect_nodequeue() {
  drupal_goto('admin/structure/nodequeue/featured_jobs/view/1');
}

function taskmenuextras_user_has_role($user, $roles = array()) {
  foreach ($roles as $role) {
    if (in_array($role, $user->roles)) {
      return TRUE;
    }
  }
  return FALSE;
}


Is there a module that can display items in database? after a few rounds of research, seems like Drupal is the way to go to manage data, but I'm fairly new to this...

I want to build a website that displays entries in the form of a table from a database.

For example,
1. User type in words of interest in the search bar
2. Data will be retrieved and displayed, which they can use for comparison (ie between data 1 and data 2)

One very similar example is like,
http://www.eigenfactor.org/

Your help is greatly appreciated

You can use views module to display list of content.

  Views module provide functionality to admin to display list of content
  in any format without using code.

If you want to implement autocomplete functionality with views, then you can use views autocomplete filters module.

  Views autocomplete filters module provide functionality to set
  autocomplete to node title or any fields.


Using wildcards in custom module outputting sql query It has become obvious to me that SQL syntax is a little different within drupal.

After some fiddling around I am getting the hang of it, but I haven't been able to use wildcards succesfully.

$sql = 'SELECT name Nombre, mail Email  FROM users WHERE status = 1 AND mail LIKE ('%@hotmail%') LIMIT 25';

Do you have any suggestion? I haven't been able to find (or I might be looking in the wrong places) for Drupal documentation regarding wildcards within $page_content in a module.

Your code has the following errors:

The string delimiter for the query is the single quote character, which is the same delimiter you use for the string inside the query.
The table names are always surrounded with { and }, which allows Drupal to prepend the prefix set in settings.php to the table name.
If you need to use the % character as wildcard character, you need to escape it with another %, in a query passed to the database API.
If you need to limit the number of returned rows, in Drupal you use db_query_range() that allows to use a query that is compatible with every database engine for which there is a driver for Drupal.
If you look at the code used from that function for different database engines, you will notice it will use a different syntax for different database engines, such as:

MySQL/MySQLi

$query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
$query .= ' LIMIT ' . (int) $from . ', ' . (int) $count;

PostGreSQL

$query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
$query .= ' LIMIT ' . (int) $count . ' OFFSET ' . (int) $from;

Your code should be written as the following one:

$sql = "SELECT name, mail FROM {users} WHERE status = 1 AND mail LIKE '%%@hotmail%%'";
$result = db_query_range($sql, array(), 0, 25);

while ($row = db_fetch_object($result)) {
  // $row->name contains the username, and $row->main contains the email address.
}

This is code taken from a Drupal module that uses the LIKE operator:

  $query = "SELECT url, COUNT(url) AS hits, MAX(timestamp) AS last FROM {accesslog} WHERE url NOT LIKE '%%%s%%' AND url <> '' GROUP BY url";
  $query_cnt = "SELECT COUNT(DISTINCT(url)) FROM {accesslog} WHERE url <> '' AND url NOT LIKE '%%%s%%'";

The query uses 5 % because the first 2 are for using % as wildcard, the third is for the "%s" placeholder, and the last two are again for using % as wildcard.

This is an example of code used by a module that limits the number of rows the query returns:

        $sql = db_rewrite_sql("SELECT n.nid, n.title, l.comment_count, l.last_comment_timestamp FROM {node} n INNER JOIN {term_node} tn ON tn.vid = n.vid INNER JOIN {term_data} td ON td.tid = tn.tid INNER JOIN {node_comment_statistics} l ON n.nid = l.nid WHERE n.status = 1 AND td.vid = %d ORDER BY l.last_comment_timestamp DESC");
        $result = db_query_range($sql, variable_get('forum_nav_vocabulary', ''), 0, variable_get('forum_block_num_0', '5'));
        $content = node_title_list($result);

The query string is passed to db_rewrite_sql(), but that is irrelevant, here; the code would not change if it didn't need to use db_rewrite_sql().


How to Delete A Field and Retain Its Value? I created a new field called field_code_file and I transferred all the value from field_code. Reference here.

Now if I delete the old field called field_code, the value in field_code_file is also deleted. So how can I delete field_code by retaining the value in field_code_file?

BTW, not only the value that is being deleted but also the files. What I'm doing is simply restore the files from the backup. The only problem I have is to retain the value in the table, whatever table it is.

Anyone can help me, please?

I'm not sure this can help you, but one solution that I can suggest is to update your nodes (instead of directly querying the database): transfer one field values to the second one and save it then delete the first one. You can use entity_metadata_wrapper or just functions that are provided by node module.
You can try something like this... Example:

$nodes = node_load_multiple(array(), array('type' => 'MY_CONTENT_TYPE'));
foreach($nodes as $node) {
  $node_wrapper = entity_metadata_wrapper('node', $node);
  $field_code = $node_wrapper->field_code->value();
  $node_wrapper->field_code_file->set($field_code);
  $node_wrapper->save();
}


How to insert form in DataBase I created my form but inserting the base does not work also radios type does not appear in the form

<?php

/**
 * @file
 * Contains \Drupal\contact_form\Form\ContributeForm.
 */

namespace Drupal\contact_form\Form;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ChangedCommand;
use Drupal\Core\Ajax\CssCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\InvokeCommand;

/**
 * Contribute form.
 */

class ContributeForm extends FormBase implements FormInterface{
    protected $accepted_domains = ['gmail.com', 'yahoo.com'];

    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'contact_form_contribute_form';
    }

    /**
     * {@inheritdoc}
     */

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

        $form['FullName'] = array(
            '#type' => 'textfield',
            '#title' => $this->t('Full Name'),
            '#required' => TRUE,

        );
        $form['Email'] = array(
            '#type' => 'email',
            '#title' => $this->t('Email address'),
            '#required' => true,
            '#size' => 60,
            '#maxlength' => 128,

        );

        $form['Feedback'] = array(
            '#type' => 'radios',
            '#title' => $this->t('Feedback'),
            '#description' => t('Type of feedback'),
            '#default_value' => 0,
            '#options' => array(
                0 =>'Comments or suggestions',
                1 => 'Questions',
                2 =>'Report a problem(s)',
                3 =>'Other',
            )
        );
        $form['Subject'] = array(
            '#type' => 'textfield',
            '#title' => $this->t('Subject'),
            '#required' => true,
        );
        $form['Message'] = array(
            '#type' => 'textarea',
            '#title' => $this->t('Your Message'),
            '#required' => true,
            '#cols' => 90,
            '#rows' => 10,
        );

        $form['captcha'] = array(
            '#type' => 'captcha',
            '#captcha_type' => 'recaptcha/reCAPTCHA',
            '#title' => $this->t('Captcha:'),
            '#required' => true,
        );

        $form['save'] = array(
            '#type' => 'submit',
            '#input' => TRUE,
            '#value' => 'save',
            '#submit' => array('buildForm')
        );

        return array(
            '#form' => $form,
            '#theme' => 'contribute',

        );

    }

    /**
     * {@inheritdoc}
     */

    public function validateForm(array &$form, FormStateInterface $form_state) {
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        $name = $form_state->getValue('FullName');
        $email = $form_state->getValue('Email');
        $subject = $form_state->getValue('Subject');
        $type = $form_state->getValue('TypeFeedback');
        $msg = $form_state->getValue('Message');
        $field = array(

            'FullName' =>  $name,
            'Email' => $email,
            'TypeFeedback' =>  $type ,
            'Subject' => $subject,
            'Message' =>  $msg,
            'Etat_message'=>  '',
            'Date_contact'=>  '',
            'adresse_IP'=>  '',
        );
        db_insert('contact')
            ->fields($field)
            ->execute();
        drupal_set_message("succesfully saved");

    }
}

Removing the #submit key fixed the submission issue for me:

$form['save'] = array(
    '#type' => 'submit',
    '#input' => TRUE,
    '#value' => 'save',
    //'#submit' => array('buildForm')
);

DB insert works correctly.

If you do return $form; in the buildForm() method, the radios form element is rendered correctly. Looks like your theme might be causing the issue.


Why doesn't my token redirect to the previous url? I thought I could use the following code:

<a href="user/login?destination=<?php print token_replace('[current-page:url]'); ?>a link

to redirect users to the page they were on after log in, but it doesn't seem to work.

I can see the correct url on the login page, e.g.:

  mysite/user/login?destination=the url of the page I was on

but when I login I am still redirected to mysite/users/my user name.

If you want to Redirect to previous drupal page after login, you can try this.

print l("Login","user/login",array('query' => drupal_get_destination()));

see drupal_get_destination


Getting front page blocks to show on redirected front page Here's what I did

I have working content pages I like
I want to have the latest of these display as the front page of my site
When that node displays as the front page, I'd like a few additional blocks to display.    This was easy to solve by configuring the blocks to only show on <front>
I built a view to show the latest page, creating a "node page" display, with "single node" as the style (from Top Node module). I sort by Node: post date. I give it the path "latest"
I set "latest" as the front page of my site.
The front page now goes to the latest node, but the front page only blocks do not display. When I check the source, the body tag does have class "front", but the blocks aren't showing. I tried setting the block configuration to show on page "latest", but that didn't work either.

How do I get the blocks to show? I don't want to build an all new front page using views because I have some programatic things in my template.

My problem appeared to be with the Top Node module. Apparently, the views display it introduces redirects in a way that causes the <front> tag not to work as it should. The answer is actually quite simple, and honestly makes the Top Node module seem a bit redundant. Although it's not intuitive to me, under "Row Style" on views, you can specify full node content, which, as the name implies, renders node results as they would appear if you typed in the URL directly. I simply made a view that returned one result, Row Style set to full node, and then created a page display at the URL "latest". Problem solved.


Wrap text fields with custom HTML I have a content type with body tag. I want to add content which has a repeating HTML mark-up.

Example:

Main Content 1

Main Content 2

This pattern repeats itself except for the text within the
 tag. Right now I'm typing tons of repeating HTML code into the body of the content type. It would be helpful if I could just focus on the main content and not on the repeating mark-up which could save lots of time.

Is there a way to surround fields with custom HTML tags, so that I can focus on the main content and not on the HTML mark-up?
Is there a module that I can use to do the same?

There are a number of ways you can handle this. The three best that come to mind are:

Use a theme hook template file to modify the output. You can do this at either the field level or the content type level.
Use Display Suite to create a field template.
Create a custom field formatter with Custom Formatters module. This plays nicely with display suite.

In your case Display Suite is probably overkill unless you wanted to use it for managing all your output. It’s an extremely powerful module that if implemented correctly allows you to not have to manipulate template files.

In either case I would suggest taking a good look at Display Suite as it really speeds up the theming process.


How can I programmatically insert date field values? I have a bunch of values from a .sql export that are in the datetime format (same format that date fields take in the DB). I'm creating nodes using these date values. How can I insert these values into the date field?

I tried:

$node->field_data_field_date['und'][0]['field_date_value'] = $datetime_value;

but it didn't seem to work. Any ideas? Thanks!

If your field's name is field_date you should access it by using

$node->field_date['und'][0]['value'] = $datetime_value;

And if it has an "end" date you have to set its value2 property.

Try to install devel, create a node for the content type you want to use and go to the devel tab node/123/devel to explore its object.


Views custom sorting How can I create a custom sort of items in a view? For example, I want to order content by: (rating * 10) - age in hours. (Rating is 5 star module percentage.)

I've been looking at the Computed Field module and the Views API but I'm not finding what I need.

In the end I created a custom module with a Views Sort handler to write the custom ORDER sql.

function custom_module_views_query_alter(&$view, &$query) {
  if($view->name === 'viewname') {
    /**
     * Order = (rating * 10) – (hours old / 2)
     * Note: the rating field is divided by 2 because in the DB the rating is out of 100
     */
    $view->query->orderby[0]['field'] = "(if(field_data_field_rating.field_rating_rating, field_data_field_rating.field_rating_rating,0) / 2) - ROUND((UNIX_TIMESTAMP(NOW())-created)/60/60/2)";
    $view->query->orderby[0]['direction'] = "DESC";

    $view->query->orderby[1]['field'] = "created";
    $view->query->orderby[1]['direction'] = "DESC";
  }
}

For this to work you either have to add the SQL JOINS in this module or add the rating and posted date fields as a 'sort' in your view.


Can PhpStorm autocomplete methods in Drupal::service? Are there anyway to get phpStorm to autocomplete \Drupal::service("xxxx")->..

[https://api.drupal.org/api/drupal/core!core.services.yml/8 For complete reference of Drupal8 service 1

For example
Typing .. \Drupal::service("config_factory")->g should show "get" in autocomplete popup list

This would be very handy for services from third-party developer also.

The auto-complete suggestions are based on the type of return value documented in the \Drupal::service() doxygen comment. Since the method may return service of any kind the type of return value is mixed.

That means auto-complete is not possible unless you explicitly specify type of the service.

/** @var \Drupal\Core\Config\ConfigFactoryInterface $config_factory */
$config_factory = \Drupal::service('config.factory');

For some particular services you can use dedicated  methods like \Drupal::configFactory() or \Drupal::config() which have properly documented return value.

Notice that generally dependency injection is more preferable method for accessing services.


How to always show poll results view instead of vote view on poll single node? The default poll runtime settings don't fit our needs. We need to have a time window with a specific start date and a specific end date. When it's too early the button and radio inputs will be hidden. I solved that by a simple hook_form_alter(). But when it's too late the results view should be displayed and I can't find out how.

All anonymous users.

I know I could hook_init() everybody to the node/%nid/results URL. Problem is, this URL gets unavailable when the user already voted. How does Drupal know if someone already voted? How can I call the clean URL alias of a node and ensure that always the results view will be displayed even when the poll settings still say the poll is open?

It's template_preprocess_node() to hook in :D

function MYTEMPLATE_preprocess_node(&$vars) {
  // check if we are in the right place
  if ($vars['type'] == 'poll') {
    if ( /* add other conditions here if you need to */ ) {
      // then unset the voting view first
      unset($vars['content']['poll_view_voting']);
      // and add the results view instead
      $node = node_load($vars['nid']);
      $vars['content']['poll_view_results'] = array('#markup' => poll_view_results($node, TRUE, FALSE));
    }
  }
}


Calls wrong image file path I have simple Image field, its file path is set to field/image so when you upload a file, its path is something like /sites/default/files/field/image/image.jpg.

But when I create content and upload the file, first of all, the thumbnail preview doesn't show up and when saved, the image is not loaded, because for some reason it's calling a wrong path of sites/default/files/styles/large/public/field/image/image.jpg.

But why? Why that path? There's no such path. Who is calling the wrong URL? It should call the correct path where the picture was uploaded and that's /sites/default/files/field/image/image.jpg.

I've tried using "Original Image" for the image field display, instead of the "Large" style, but no matter what I use, /styles/large/public/ is added to the URL.

Permissions are correct on the /sites/default/files folder (the original image is uploaded successfully), there are no related errors in the dblog report, and there's no problem with GD/Imagemagick in the status report.

What could be adding the extra part to the image URL?

You might simply be editing the wrong "display". Happened to me :)

If you have the Display Suite Drupal module installed, node types can each have several option sets (called "displays") how to display their fields, and a template or view then selects one of them to show the node. With the Taxonomy display Drupal module, the same is possible for taxonomies.

In these cases, you might simply be trying to adapt the image style setting in the wrong display. Check if you have a second line of tab-like options (starting with "Standard") for either nodes or taxonomies. In that case you have multiple displays for this node type / taxonomy, and you have to configure the image type for the right one.

You'll have to visit one of these admin menu items to check for displays:

"Structure → Content Types → [your content type] → Manage Display"
"Structure → Taxonomy → [your taxonomy] → Manage Display"


How do I output the link to the content? In a view, I've got a field set up to output the link to the content.

I'm not sure how to reference it in my views-view-fields.html.twig file. I'm referencing all of the other fields values properly as they all work, but that main anchor link just isn't coming out. What is the proper syntax?

 {{ fields.uri.content }}

{{fields.field_work_page_tagline.content}}

{{fields.title.content}}

This works for me in views-view-fields.html.twig

{{ fields.view_node.content }}

The code above will directly display the value of "Content: Link to Content".

Hope this helps.


How do I get the node ID from the view's URL? I want to add a comment form to my view by using the following code:

print drupal_get_form('comment_node_project_form', array('nid' => $node->nid), 'comment');

However, it shows up a error saying that the variable $node->nid is undefined. I then realized it is a view, not a node.

In the view, by choosing the right URL, e.g. /projects/{username}/{nodeid}, I only show one content.

I guess I can get the node ID by parsing the 3rd argument of the URL. How do I get the node ID from the view's URL?

If the view uses fields, you can add a field labeled Content: Nid - and either build the link in the template by yourself or try to Rewrite the field in the Views admin UI. If the View uses display views, such as Teaser, you should be able to use the $node variable in the teaser (in this case) tpl file.


How to delete 1600 users and 2500 posts? A couple years ago I configured a site with Drupal 6.9, and then I forgot about it. I have 160 pages of users that are all spammers and I need to delete all but 3. Doing this one page at a time is painfully slow due to the MySQL calls (I guess). I also have about 2500 forum posts to delete.

I'm a little afraid to delete records from the database directly.

I saw a module called "mass delete", but it is for Drupal version 5 and not available for version 6.

You can use Views Bulk Operations, a module that allows to execute bulk operations on nodes, users, comments; it also permits to apply the selected operation to all the nodes, users, or comments using the Batch API. The batch API allows forms processing to be spread out over several page requests, thus ensuring that the processing does not get interrupted because of a PHP timeout, while allowing the user to receive feedback on the progress of the ongoing operations.


Overriding permissions of existing page blocks all users Problem

I'm trying to block access to Drupal's taxonomy pages for anonymous users.

I'm using the solution set out in this answer, but for Drupal 7 rather than 6.

I'm using hook_menu_alter and hook_permission to create a new access argument for taxonomy pages. The permission is successfully created, but no matter what roles I tick the pages remain blocked. Any ideas what I'm doing wrong?

Example Code

function custom_module_menu_alter(&$items) {
  $items['taxonomy/term/%']['access arguments'] = array('access taxonomy permission');
}

function custom_module_permission() {
  return array(
    'access taxonomy permission' => array(
        'title' => t('Access taxonomy pages'),
    )
  );
}

Is there any special reason that you're using 'taxonomy/term/%' instead of 'taxonomy/term/%taxonomy_term' in your implementation of hook_menu_alter()? If not, I would change that and clear the cache, see if it helps.

Edit...Here's a code example from the Term Per Role module:

function term_per_role_menu_alter(&$items) {
  $path = 'taxonomy/term/%taxonomy_term';
  if (isset($items[$path])) {
    $items[$path]['page arguments'] = array_merge($items[$path]['page arguments'], array($items[$path]['page callback']));
    $items[$path]['page callback'] = 'term_per_role_taxonomy_term_page';
  }
}

(A module which I would have recommended but the last commit on the project was over 3 years ago.)


Adding jQuery to Drupal 7 site: drupal_add_js() adds but doesn't call? I'm using jQuery accordion effects to display some information. I include the libraries:

    drupal_add_js('http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', file);
    drupal_add_js('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js', file);

Those seem to work fine, since after including them I can paste

jQuery(".accordion").accordion({collapsible:true,active:false});

into scratchpad and I get the functionality I want.

However, if I try to add it to my function like so:

drupal_add_js('jQuery(".accordion").accordion({collapsible:true,active:false});', inline);

...nothing happens. I've tried some variations, such as

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

as well as moving the drupal_add_js() call further downstream in my code, so it appears after the elements it acts on are created and rendered.

How do I get this little snippet of code to run on my page?

You're most of the way there!  You just need to convert what's in your ready() to a function:

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

Also, according to docs you should change your googleapi calls from file to 'external',

drupal_add_js('http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', 'external');


ctools_ajax_command_redirect is no longer working to redirect ajax form on successful submit My ajax callback function which is changing a form did redirect properly in the past, but now with no change to this code it does not work anymore.

function node_create_callback($form, &$form_state){
    module_load_include('inc', 'node', 'node.pages');
    node_form_validate($form, $form_state);
    if (!form_get_errors()){

      //on success submit form and redirect
      node_form_submit($form,$form_state);
      ctools_include('ajax');
      ctools_add_js('ajax-responder');
      $commands =  array(ctools_ajax_command_redirect("node/"));
      return array('#type' => 'ajax', '#commands' => $commands);
    }
    else
    {
      //on error display errors on form without refreshing page
      $commands = array('#type' => 'ajax', '#error' => FALSE, '#commands' => array());
      $output = drupal_render($form);
      $commands['#commands'][] = ajax_command_insert(NULL, $output);
      // Prepend status messages to the node form.
      $commands['#commands'][] = ajax_command_prepend(NULL, theme('status_messages'));
      return $commands;
    }
}

instead of

  return array('#type' => 'ajax',  '#commands' => $commands);

try this

  print ajax_render($commands);

  drupal_exit();

I had a similar problem, and this code worked for me.

courtesy: Ajax redirect on successful submission is not working properly

Hope that helps!


Why doesn't the token for the node title work? In Drupal 8, I activated the Message module and the Message Example sub-module.

These are the fields I added to the template to create a message when a new comment is created.

This is the content of the message.

  1) [message:node-title]
  2) [message:field_node_reference:entity:title]

These are the tokens that are listed as available.

[message:node-title] is replaced from the title of the parent node, but [message:field_node_reference:entity:title] is not replaced. Why?

[message:field_node_reference:entity:title] is not replaced with the node title because, for a example_create_comment message template, the field_node_reference field doesn't contain any valid node reference.

In fact, the Message example module uses the following code to return the value of the [message:node-title] token. (See message_example_tokens().)

    case 'node-title':
      if ($message->bundle() == 'example_create_comment') {
        $replacements[$original] = $message->field_comment_reference->entity->getCommentedEntity()->label();
      }
      else {
        $replacements[$original] = $message->field_node_reference->get(0)->entity->label();
      }
      break;

When the message bundle (the message template) is example_create_comment, it gets the node title using the field_comment_reference field ($message->field_comment_reference->entity->getCommentedEntity()->label()), not the field_node_reference field that is used for the other message templates.

The [message:field_node_reference:entity:title] token is added from the Token module, which adds a token for each field a content entity has. (Message is a content entity, and Message template is its bundle.) The Token module doesn't know if there is another field to use when the field_node_reference field doesn't contain any valid reference, so the token is not replaced.

If you want to get the node title in any case, you need to use the [message:node-title] token.


Using node author information in a module (efficiency) Problem

I'm building a module to let users apply to a job. The user goes to a job advert, presses apply and it sends their CV to the author of the job advert.

I have it working, but I'm worried that the way I grab the users email is inefficient and I was wondering if there was a better way to do it.

Current Set-up

I have a custom form with a submit function. I grab the email of the author of the current node using the following:

function jobapplication_form_submit($form, &$form_state) {
    if(arg(0) == 'node' && is_numeric(arg(1))){
            $node = node_load(arg(1));
            $user = user_load_multiple(array(),array('uid' => $node->uid));
        };
    $email = $user['1']->mail;

Is there a way to get the node author email without having to load the entire node? It seems really inefficient (at least to my inexperienced eyes).

It is a standard issue of efficiency versus convenience. You can, of course, simply join {node} and {users} tables on uid field and do it in simple select, taking just that one field you really need. And indeed it will be faster. But you will need to rebuild that part of the code if some day one of these tables will get renamed or restructured. That's why people are using CMS in the first place - to stop worrying about low level and get the job done simple and easy. Computers are cheaper than people these days.

It is possible that you will save a second of CPU time and 30kB of RAM. So what? Do you really expect so high traffic that it'll be a problem? Databases cache their results in RAM too, so it might be actually faster, overall, to always read whole node. It means one node set to cache instead of dozen sets with different fields selected. Or might not. It depends on to many variables to know, so it seems usual to considered adjusting these variables better than complicating code.


Create new content type on hook_install Can someone show me a proper example of how to create a new content type in a module's hook_install method?

I'd also like to know if/what I should do during hook_uninstall to clean up my mess; I read there is some debate about simply removing the content.

I haven't been able to find an example of the proper method of accomplishing this task, any help would be appreciated!

One of the best ways to keep this information in code is to use features. Feaures can put into code:

Content types
CCK fields
Permissions
Roles

The list goes on.

One nice feature about features is the drush integration

drush features will give you a list of all features on the site, and their status
drush features revert all will revert all features back to what is in code (really handy for running after deployments)

Help this helps


How to create a view filter plugin to filter a column created by a view field plugin I have created a view field plugin to display an "internal status" for each node in a view.
Those status are not stored in a table (and should not) because each status may vary depending the current date (and some other fluctuating data).
The possible status outputted by this virtual field (not sure it is the correct terminology) are 1,2 or 3 (integer)
Here is the simplified code
1-Declare the virtual field in hook_views_data_alter()
function mymodule_views_data_alter(array &$data) {
  $data['node']['internal_status'] = [
    'title' => t('Internal Status'),
    'field' => [
      'title' => t('Internal Status'),
      'help' => t("Display internal status"),
      'id' => 'internal_status',
    ],
  ];
}

2- Create the view plugin
/**
 * Field handler to display internal status.
 *
 * @ViewsField("internal_status")
 */
class NodeInternalStatus extends FieldPluginBase {

  public function query() {}

  public function render(ResultRow $values) {
    $node = $values->_entity;
    $value= return_1_2_or_3_depending_on_dyn_data_like_the_current_date($node);
    switch ($value){
      case 1:
        return t('This is 1');
      case 2:
        return t('This is 2');
      case 3:
        return t('This is 3');
    }
    //will never go here if everything is ok
    return t('n/a');
  }
}

My Question: I would like to create a filter plugin to filter nodes according their internal status [by using return_1_2_or_3_depending_on_dyn_data_like_the_current_date($node)]
I have tried to extend the inOperator class but as the real column of the "internal status" field doesn't exists in the DB, I keep getting the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'node_field_data.internal_status' in 'where clause':

After some digging I will answer myself to this question: it is not possible to create a filter on a non existent DB column.
How to solve this issue:
In my example, the values of this non existent column are calculated via the function return_1_2_or_3_depending_on_dyn_data_like_the_current_date($node).
We couldn't use this function to create the filter. Instead, for each value returned by the function (in my case 1,2 or 3), we have to write a query with the same logic used in the "dropped" function.
All the logic must reside in the query method of the filter plugin.
Here is an example:
1- Add the filter in hook_views_data_alter
function mymodule_views_data_alter(array &$data) {
  $data['node_field_data']['internal_status_filter'] = [
    'title' => t('Filter by Internal Status'),
    'filter' => [
      'title' => t('Filter by Internal Status'),
      'help' => t('Bla bla'),
      'id' => 'internal_status_filter',
    ],
  ];
}

2-Create the filter plugin (In my case, I have extended the inOperator Class)
/**
 * Filters the internal status of a node
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("internal_status_filter")
 */
class InternalStatus extends InOperator {

  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->valueTitle = t('Available Status');
    $this->definition['options callback'] = array($this, 'generateOptions');
  }

  public function query() {
    $configuration = [
      'left_table' => 'node_field_data',
      'left_field' => 'nid',
      'field'      => 'entity_id',
      'type'       => 'LEFT',
      'extra_operator'   => 'AND',
    ];
    if (
    $selected_status = $this->value[0];
    if ($this->operator == 'in') {
      $this->ensureMyTable();
      switch ($selected_status) {
        case (1):
          //Add a condition on another field
          $table_field='node__field_another_field';
          $configuration['table']=$table_field;
          $join = Views::pluginManager('join')->createInstance('standard', $configuration);
          $this->query->addRelationship($table_field, $join, 'node_field_data');
          $this->query->addWhere('AND', "${table_field}.field_simulation_is_past_value", 1, '=');
          //Add as many condition to get what you need
          break;
          ....
       }
     }
  }

  public function generateOptions() {
    return [
      1=>'Status 1',
      2=>'Status 2',
      3=>'Status 3',
    ];
  }

Make sure that your annotation at the top of the file @ViewsFilter("internal_status_filter") is the same id than the ones defined in hook_views_data_alter