How to concatenate a string in a WHERE clause of an SQL query? I'm trying to execute the following query but when I append the 'n.nid = "node/" + ua.source' condition I'm getting an error page:

        $query = db_select('node', 'n')->extend('PagerDefault');
        $query->join('url_alias', 'ua', 'n.nid = "node/" + ua.source');
        $nids = $query
            ->fields('n', array('nid', 'sticky', 'created'))
            ->condition('type', 'news')
            ->condition('status', 1)
            ->orderBy('sticky', 'DESC')
            ->orderBy('created', 'DESC')
            ->limit(3)
            ->addTag('node_access')
            ->execute()
            ->fetchCol();

Any suggestions to resolve this?

There is a small changes in code. I think it will help you.

$query = db_select('node', 'n')->extend('PagerDefault');
        $query->join('url_alias', 'ua', "ua.source = CONCAT('node/', n.nid)" );
        $nids = $query
            ->fields('n', array('nid', 'sticky', 'created'))
            ->condition('type', 'news')
            ->condition('status', 1)
            ->orderBy('sticky', 'DESC')
            ->orderBy('created', 'DESC')
            ->limit(3)
            ->addTag('node_access')
            ->execute()
            ->fetchCol();

For more info check


Webform: Hide the "add more" button I would like to get rid of the ajax "add more items" button at the bottom of a multiple elements form item.

The D8 webform I'm building has a custom composite element with multiple values allowed. The table form display has nice + and – buttons in each row. The "Add x more items" element below the table is not needed.

In the advanced tab, under "Multiple settings", there is only an option to hide the +/– buttons, not the "Add x more items" element.

Additional information:

Webform module version: 8.x-5.0-rc7
YAML Source (excerpt):

   fieldset_teilnehmer:
    '#type': fieldset
    '#title': Teilnehmer
    teilnehmer:
      '#type': custom_composite
      '#title': Teilnehmer
      '#required': true
      '#required_error': 'Bitte tragen Sie die Teilnehmer ein.'
      '#multiple__label': Teilnehmer
      '#multiple__labels': Teilnehmer
      '#multiple__min_items': '5'
      '#multiple__empty_items': '5'
      '#multiple__sorting': false
      '#element':
        teilnehmer_name:
          '#type': textfield
          '#title': Name
        teilnehmer_alter:
          '#type': select
          '#options':
            18: ≥18
            17: 17
            16: 16
            15: 15
            14: 14
            13: 13
            12: 12
            11: 11
            10: 10
            9: 9
            8: 8
            7: 7
            6: 6
            5: 5
            4: 4
            3: 3
            2: 2
            1: 1
            0: 0
          '#title': Alter

If you set the
"Minimum amount of items" and
"Number of empty items" to the same number the add more won't appear.

Here is a screenshot

Here is the YAML source for basic multiple text field

textfield:
  '#type': textfield
  '#title': textfield
  '#multiple': 5
  '#multiple__min_items': '5'
  '#multiple__empty_items': '5'

Here is the YAML source for multiple custom composite

custom_composite:
  '#type': custom_composite
  '#title': custom_composite
  '#multiple': 5
  '#multiple__min_items': '5'
  '#multiple__empty_items': '5'
  '#multiple__sorting': false
  '#multiple__operations': false
  '#element':
    textfield:
      '#type': textfield
      '#title': textfield
    select:
      '#type': select
      '#options': days
      '#title': select


composer update drupal/drupal does not work : Nothing to install or update I’ve installed several Drupal 8 site with composer as it is strongly recommended.

I can update modules like this :

composer require drupal/pathauto:1.1

But I can't update core with

composer update drupal/core --with-dependencies (as seen in documentation)

or (think should be like this in my case) :

composer update drupal/drupal --with-dependencies

I try tu update from 8.4.2 to 8.5.0 in this website.

I’ve read a lot of topics on this, I’ve tried :

remove folder /vendor
remove composer.lock

But it didn’t work.

How can I update my classic Drupal (nothing fancy in it) with composer ? Should I gave up and update with Drush ?

Her is my composer.json

{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
        "composer/installers": "^1.0.24",
        "wikimedia/composer-merge-plugin": "^1.4",
        "drupal/contact_block": "^1.4",
        "drupal/twig_tweak": "^1.9",
        "drupal/contact_ajax": "^1.4@beta",
        "drupal/pathauto": "1.1",
        "drupal/easy_breadcrumb": "^1.6",
        "drupal/redirect": "1.1",
        "drupal/views_slideshow": "^4.6",
        "drupal/bootstrap": "3.11",
        "drush/drush": "dev-master"
    },
    "replace": {
        "drupal/core": "^8.4"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php.",
            "This file specifies the packages.drupal.org repository.",
            "You can read more about this composer repository at:",
            "https://www.drupal.org/node/2718229"
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        },
        "installer-paths": {
            "core": ["type:drupal-core"],
            "modules/contrib/{$name}": ["type:drupal-module"],
            "profiles/contrib/{$name}": ["type:drupal-profile"],
            "themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"],
            "modules/custom/{$name}": ["type:drupal-custom-module"],
            "themes/custom/{$name}": ["type:drupal-custom-theme"]
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": [
          "Drupal\\Core\\Composer\\Composer::ensureHtaccess"
        ],
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
    },
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ]
}

Finally, i could update with these modifications.

Step 1, optional in case your composer.jsoncontains this. If it is ok, apply step 2

add

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

remove

"replace": {
    "drupal/core": "^8.4"
},

Step 2

delete this folder :

vendor

delete this file :

composer.lock

run

composer update --with-dependencies


Custom field widget with text field formatter? I'm trying to create a compound field in Drupal 7 that combines and image field, text field and a textarea field.

I've successfully done this but I'm now trying to add text format option to the textarea and I'm having problems getting it working.

It seems that when I change the widget's textarea field into a text_format field Drupal expands that field into two fields value and format (see: filter_process_format), this means that when the node displaying the field is saved it stores the array into the database and not the field value.

Here is my widget:

/**
  * Implements hook_field_widget_form().
  */
function MYMODULE_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

    $elements = image_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);

    foreach (element_children($elements) as $delta) {
        foreach ($elements[$delta]['#process'] as $key => $process) {
            if($process == 'image_field_widget_process') {
                unset($elements[$delta]['#process'][$key]);
            }
        }
      $elements[$delta]['#process'][] = 'MYMODULE_widget_process';
    }

    return $elements;
}

/**
 * Element #process callback function.
 *
 * @param array $element
 * @param arrayreference $form_state
 * @param array $form
 * @return array
 */
function MYMODULE_widget_process($element, &$form_state, $form) {

    $element = @image_field_widget_process($element, $form_state, $form);

    $item = $element['#value'];
    $item['fid'] = $element['fid']['#value'];

  $instance = field_widget_instance($element, $form_state);

    $settings = $instance['settings'];
    $widget_settings = $instance['widget']['settings'];

    $element['title'] = array(
        '#type' => 'textfield',
        '#title' => 'Title',
        '#default_value' => isset($item['title']) ? $item['title'] : '',
    );

    $element['text'] = array(
        '#type' => 'textarea',
        '#title' => 'Text',
        '#default_value' => isset($item['text']) ? $item['text'] : '',
    );

    if($instance['settings']['text_processing']) {
      $element['text']['#type'] = 'text_format';
      $element['text']['#format'] = isset($item['format']) ? $item['format'] : NULL;
      $element['text']['#base_type'] = 'textarea';
    }

    return $element;
}

The field value in the database is "Array" and not the string the user entered. If the field is set to a normal textarea the field value is stored correctly.

I'm guessing this is something to do with the structure of the widget but I can't work it out and the documentation is non existent.

I recently needed to create a widget for file field, that among other things needed to be able to handle multiple uploads via plupload.

Anyways, during the process of getting everything to work, I discovered the #value_callback attribute that you can put on a form item. It allows you to change the data of the submitted data and extra extra infomation, like fid of a file.

This isn't documented yet, but you can take a look at it's use in the file module. There is an issue for this on the Drupal issue tracker, but no good patch has been created with some document example yet.

I'm not sure if this would be a good case for the use of #value_callback, but it seems to me, that it could be of good use in this case.


Twig date function not working on custom field within node Even if content.field_my_date contains a date like 2021-10-01, twigs date function outputs today's date when using {{ content.field_my_date|date("M.d.Y") }}. Simply printing {{ content.field_my_date }} to make sure the field isn't empty, outputs the correct date and label.

Before you need convert field field_my_date form 2021-10-01 to timestamp

You can use hook_ENTITY_TYPE_view_alter to be convert it to timestamp

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;

/**
 * Implements hook_ENTITY_TYPE_view().
 */

function hook_ENTITY_TYPE_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  if($display->bundle()=='node_type'){
    $field_date_timestamp = strtotime($entity->get('field_my_date')- >value);
    $build['field_my_date'] = \Drupal::service('date.formatter')->format(
    $field_date_timestamp, 'custom', 'M.d.Y');
  }
}

in file twig node tempalte {{field_my_date}}


How to check whether a username already exists? I had created a controller where I can create a new user programmitically by the following code.

$user = User::create();

      //Mandatory settings
      $user->setPassword($password);
      $user->enforceIsNew();
      $user->setEmail($email);

      //This username must be unique and accept only a-Z,0-9, - _ @ .
      $user->setUsername($username);

      //Optional settings
      $language = 'en';
      $user->set("init", 'email');
      $user->set("langcode", $language);
      $user->set("preferred_langcode", $language);
      $user->set("preferred_admin_langcode", $language);
      $user->activate();

      //Save user
      $user->save();
      drupal_set_message("User with uid " . $user->id() . " saved!\n");

      $uid = $user->id();

I am passing all variables via postman by POST method. I am using email as the username. But I want to check a condition (whether the username is already exist ) before the user creation. How can I write the if condition?

I guess you can use a simple EntityQuery.

  $ids = \Drupal::entityQuery('user')
        ->condition('name', 'USERNAME_TO_CHECK')
        ->range(0, 1)
        ->execute();
    if(!empty($ids)){
      //then this name already exists
    }


Converting date into unix timestamp not giving expected result Basically I was trying to get age from date of birth, for which I am using Computed Field module.

Following code was used:

$isoArray = explode ( '-', substr($entity->field_dob1[0]['value'],0,10));
$bdayunix = mktime ( 00, 00, 00, (int)$isoArray[1], (int)$isoArray[2], (int)$isoArray[0]);

$nowunix = time();
$unixage = $nowunix - $bdayunix;
$age = floor($unixage/ (365 * 24 * 60 * 60));

$entity_field[0]['value'] = $age;

When I checked the code, I found that this part of code is not giving the correct  result:

 $isoArray = explode ( '-', substr($entity->field_dob1[0]['value'],0,10));
 $bdayunix = mktime ( 00, 00, 00, (int)$isoArray[1], (int)$isoArray[2], (int)$isoArray[0]);

I can say that because when I try to convert $bdayunix into date,whatever the date of  birth is, I always get the result 1999.

ie; $dob = date("Y",$bdayunix ); always gives result:1999.

Could you please tell me where I am going wrong? Is this problem of Computed field module or I am doing some mistake in my code ?

(Date format in users bday field is yyyy-mm-dd and I have tried all types: Date, DateISO format and Date Unix timestamp).

Thank you in advance.

I found the solution .

If we select Field type as Date(Unix Timestamp) then $entity->field_dob1[0]['value'] will return unix timestamp value which can be directly used.

So if anyone in same requirement can use the following code:

$bdayunix = $entity->field_date_of_birth['und'][0]['value'];
$nowunix = time();
$unixage = $nowunix - $bdayunix;
$age = floor($unixage/ (365 * 24 * 60 * 60));

$entity_field[0]['value'] = $age;

PS: Dont forget to select field type as Date(Unix Timestamp).


In Drupal Fullcalendar, how do I add an additional field to the calendar view? I need to add one more field to the Fullcalender views. Anyone know what code I need to edit to take care of this?

There's no need to edit any code to add additional field to calendar view.

To add additional field, you need to install Views fields combine or Token module.

How to use Views fields combine:

Edit your calendar view
Add fields you want to display (from field)
Add Combined fields field and select which fields you want to display
Under format -> settings -> customize fields, check Use a custom title checkbox and select the combined fields you created on step 3
Apply changes and save your view then preview the results on the actual page/block.


Send variable to the user profile in Drupal 6 I am developing a module for Drupal which provides a login form and after submission user cURL to login in with those credentials on another website.

If all goes well, the module redirects the user to their profile and should present the information cURL fetched. This is where things go wrong.

What I'm trying to do is get the $account variable through the username. This is all in the module_name_form_submit function:

$account = user_load(array('name' => check_plain($user)));

And then append the data I want to display to it:

$account->content['module_name'] = array(
    '#title' => t('Module Title'),
    '#values' => get_info()
    );

If I do a print_r before the redirect, sure enough, the data is there as it should. But after the redirect:

$form_state['redirect'] = "users/{$user}";

I no longer have access to that same data. So the question is, how can I set that variable in a permanent way and access it after the redirect in the user profile page? (I'm trying to avoid sessions).

PHP is a "shared-nothing" architecture, nothing persists over multiple requests unless stored externally.

So you really only have two options:

Sessions. Drupal already maintains a session for you for every user (also anon users, except on the first request). So just add your data to $_SESSION['yourmodule']['yourdata'] and you have it available on the next request where you can remove it again if you want.
GET. Alternatively, you can also pass the data forward through the GET request, by doing the redirect like this: $form_state['redirect'] = array('user/' . $account->uid, array('key' => 'value')). As in my example, you should always use the internal URL when doing a redirect, Drupal will take care of the aliasing fory you.


How do we fetch the list of all content types refererencing a particular taxonomy vocabulary? I am trying to delete a taxonomy vocabulary but before doing that, I want to know if there is any content type with a field referencing a taxonomy vocabulary.

My first thought was using a view, but that would only list content. Unless it can display the type and group by the type, it would not be the best solution.

If you want to check from UI then maybe you can try the Field list page (/admin/reports/fields) for checking which all the places have the required taxonomy field has been referenced/used.


How to set format of date in date field I have a content type in which I used a date field and for the same i have used this field -> https://drupal.org/project/date

My problem is I want to set the date format as  " September 13, 2013 | 3:39 UTC |"  , so I overrode the format and made it 'F j, Y \| H:i e' (refering to http://in3.php.net/manual/en/function.date.php)

but it is only showing the year (e.g. 2013| ), not other things.

Can anyone help me with this?

Path: Home » Administration » Configuration » Regional and language
Or
Path : admin/config/regional/settings

In the above path there will be tab called 'format' where you can create your own custom format where format string is F j, Y, g:i a e.
 Now you can change the date format of the field from the manage displays tab of the admin/structure/types path.
 In the respective field you will have settings options where you can set your custom date format


Custom translatable content entity appears twice when choosing the entity type to create a view I'm Developing a custom module with custom content entities that needs to be translatable. The problem is that when they are made translatable by adding:
translatable = TRUE in the @ContentEntityType annotation, the entities appear twice in the drop down view setting options (check the image, 'Faculty' appears twice) which is really strange.

I don't mind if they show twice or more than that but the problem comes when you decide which to choose to create your view because one of the options results in only the entity label field(name) available for building the view, of course along with other unnecessary fields to my use caes such as UUID, created, changed, ..etc . However, the other option has the other fields that I added
to the entity through the Manage fields UI and those are the ones I need.

I have done what this page at drupal.org stated { if the 'translatable' annotation has value TRUE}  define a class that extends \Drupal\content_translation\ContentTranslationHandler, to translate the content.

There is no handy resource to learn how to impelement the TranslationHandeler class. So I have followed the one used in core of 'Taxanomy' entity which
basically looks like it would work with any other entity. You just need to rename it! - correct me if I'm worng! Also, by the way translation of the entity works fine even in instances where I didn't define the TranslationHandaler class and I just included 'translatable = TRUE' annotation, which also is strange!!

I have tried every thing I could to fix it and researched for hours but with no luck. The two options dissappears if you don't include translatable = TRUE in the annotation but then you can not translate the entity fields this way.

My drupal version is 8.1.0 and I have used drupal console on windows to generate the module and the entities. Then I added the extra code.

Anyone could help please!

Code for defining TranslationHandeler class

namespace Drupal\registerar_office;

use Drupal\Core\Entity\EntityInterface;
use Drupal\content_translation\ContentTranslationHandler;
use Drupal\Core\Form\FormStateInterface;

 /**
 * Defines the translation handler for faculty.
 */
class FacultyTranslationHandler extends ContentTranslationHandler {

 /**
  * {@inheritdoc}
  */
  public function entityFormAlter(array &$form, FormStateInterface $form_state, EntityInterface $entity) {
    parent::entityFormAlter($form, $form_state, $entity);
    $form['actions']['submit']['#submit'][] = array($this, 'entityFormSave');
  }

  /**
   * Form submission handler for TermTranslationHandler::entityFormAlter().
   *
   * This handles the save action.
   *
   * @see \Drupal\Core\Entity\EntityForm::build().
   */
  function entityFormSave(array $form, FormStateInterface $form_state) {
    if ($this->getSourceLangcode($form_state)) {
      $entity = $form_state->getFormObject()->getEntity();
      // We need a redirect here, otherwise we would get an access denied page,
      // since the current URL would be preserved and we would try to add a
      // translation for a language that already has a translation.
      $form_state->setRedirectUrl($entity->urlInfo('edit-form'));
    }
  }

}

I don't think it's directly associated with translation handling - it looks like it's the distinction between the entity and entity_field_data table. The "working" option in the dropdown is a class derived from WizardPluginBase.

I fixed my problem by making sure both of these were in my Drupal\custom_entity\Entity\CustomEntityViewsData::getViewsData

$data['custom_entity']['table']['wizard_id'] = 'custom_entity';
$data['custom_entity_field_data']['table']['wizard_id'] = 'custom_entity';`


How can I configure CKEditor to show content in 'plain text editor'? I would like to configure my CKEditor to show content that I edit in plain text editor by default as I have some widgets on my site (e.g. Twitter) that get removed by CKEditor's rendering to rich text - how can I avoid that?

Thanks!

Assuming Drupal 7 - goto admin/config/content/formats and change the order of the text formats, placing Plain Text at the top of the list. This will default the edit format, however content that is already created would default to whatever format was used to create it in the first place.

This will however filter quite restrictively the output. If you mean to include a text format that does not perform any formatting at all, on the same page, you can 'Add Text format', label it unaltered or whatever title you prefer, set roles to administrator (very high security risk with giving this format to untrusted persons), and leave everything else blank. This will create an unaltered format which allows things like direct html, javacript and php writing in blocks, etc.


How can I use a views template to modify the titles of taxonomy links? I have a view that shows a field which is a taxonomy term reference set to display each term as a link.  The taxonomy names are quite long so I want to rewrite them using a views template.

I made a template like this:

foreach ($row->field_field_ad_purpose as $data):
  if ($data['rendered']['#title'] == 'Apples, oranges, pears, and strawberries'):
    $data['rendered']['#title'] = 'Fruits';
  print $output;

Using dpm(), I was able to confirm that the #title is in fact shortened.  However, printing $output prints out the original title.  I also tried printing $data, but this just gives Array.  What is the function to call to print out the term as a link?

You need to create another field with the 'path' and set this to not display by default within the views UI.

You can then get the 'path' variable in your template along with the 'title' variable and create your link using Drupals l() function.

   print l($data['rendered']['#title'], $path);

http://api.drupal.org/api/drupal/includes%21common.inc/function/l/7


How to enable Rich text editor for content types I have installed Ckeditor module and configured it to work with advanced editing options. But couldn't get rich text editor. I even tried all options in content authoring I din't get any solution.

And I want to enable rich text editor for certain fields and webforms. Here my case is the rich text editor should be enabled only some fields not all the fields.

For example, if i have two text fields(text areas) like summary and body. Only the body field should be enabled with rich text format the other should show basic editor. Can I have a clear answer.

Follow these steps:

Go and write in drush command prompt-

sudo drush en ckeditor -y
Use full HTML format while editing the node as shown in attached
screenshot.


How to alter breadcrumbs from my controller in my module? The breadcrumb code seems to gather everything from the URL, as it should. But in my module, the other entries used in the URL path do not represent somewhere where the user can go. They instead pass information from my form to a controller object.

Is there a way to remove these entries in the breadcrumb from my modules' controller object?

To customize your Breadcrumbs you need to take full control of the Breadcrumb for that particular route with your own Breadcrumb Builder service.

To do this, you need to create an entry in your module/profile services file:

e.g., mymodule/mymodule.services.yml

services:
  mymodule.breadcrumb:
    class: Drupal\mymodule\MyModuleBreadcrumbBuilder
    tags:
      - { name: breadcrumb_builder, priority: 100 }

You then need to create your Breadcrumb Builder class

e.g. mymodule/src/MyModuleBreadcrumbBuilder.php

<?php

/**
 * @file
 * Contains Drupal\mymodule\MyModuleBreadcrumbBuilder.
 */

namespace Drupal\mymodule;

use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Class MyModuleBreadcrumbBuilder.
 *
 * @package Drupal\mymodule
 */
class MyModuleBreadcrumbBuilder implements BreadcrumbBuilderInterface {

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    $route = $route_match->getCurrentRouteMatch();

    // Add conditionals that return TRUE when the current route should have it's
    // breadcrumb handled here.
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new Breadcrumb();
    $breadcrumb->addCacheContexts(['route']);

    // Add logic here that builds up the breadcrumbs based on desired behaviour.
    $links[] = Link::createFromRoute(t('Home'), '<front>');

    $breadcrumb->setLinks($links);

    return $breadcrumb;
  }

}

The applies method is where you register this Breadcrumb Builder to be used for the particular route, so build a conditional there that matches your route(s) and returns TRUE.

The build method is where you build your Breadcrumb for any routes that applies returns TRUE, so if you are dealing with multiple routes you will need to build the appropriate logic here to build said Breadcrumbs.

I recommend reading through Palantir's blog post for more background and details: https://www.palantir.net/blog/d8ftw-breadcrumbs-work


Multiple Webforms in one View I have 4 webforms on a site and I would like to be able to display the data from each of those in a table using a view. Each of the forms has a "First Name" "Last Name" "Phone Number" and "Email Address" field, along with other fields that are specific to the different forms. Ideally, I would like to have a table that shows those 4 fields from all of the forms along with a column that says what form it came from. Can anyone give me an idea of where to start? My assumption is that the answer is somewhere in relationships and contextual filters, but I'm still learning how all of that stuff works. Any help or advice would be greatly appreciated. Thanks!!

Well after a couple of weeks I got it to work. In case anyone else wants to do the same, here is how I did it.

I added a Webform submissions: Data Relationship for each field in each form (16 total for me....4 fields from 4 webforms). Then I added the fields for each one (again 16 total). Then I went into the Table Settings and had each of the 4 types displayed in the same column. Then I just added a Content: Title field to show which Webform the submission came from.

I don't know if that is the best way to do it, but it worked for me.


project/configuration sync from shell (not from ./admin) With project/configuration (core 7.22 and configuration 7.x-2.0-alpha2), we can sync a new database to the exported .inc files via the admin gui, but need to be able to do it from drush.

Specifically, we trying to get to where we can run drush site-install, and then drush sync config, to get content types and other meta-data built, from the project/configuration exported .inc files.

It looks like the heavy lifting is implemented in configuration.module, function configuration_import_directory.  Do we still have to roll our own, to be able to invoke this from the shell?

drush csyn does the job.

we're putting the config files in a non-default location, so need to specify the path:
  drush csyn --source=/path/to/config


localhost subsites configuration I know how to install a single instance of Drupal very well but I want to create a number of sub-sites under my Drupal installation.
My file structure is as follows:
drupal7_main
 -sites
   --drupal7_sub1
    settings.php
   --drupal7_sub2
    settings.php

I'm developing on my localhost and the plan is to duplicate the structure on the production server.
However, only drupal7_main works. When I visit localhost/drupal7_main, Drupal is ready and configurable as usual; when I visit localhost/drupal7_sub1, I get the following error.

Not Found
The requested URL /drupal7_sub1 was not found on this server.

I get the same for drupal7_sub2.
I'm trying to learn this process and would appreciate some help.

You need to create symbolic links in order that your drupal7_sub1 and drupal7_sub2 directories works. Those symlinks needs to target your drupal7_main directory.

To create a symlink, open a commandline tool and execute following commands (if your on a Windows machine). You need to put the correct paths depending your localhost configuration.

First go to root directory of your localhost

cd C:/wampp/htdocs/

Create symlink for each subwebsite (drupal7_sub1, drupal7_sub2)

mklink /D drupal7_sub1 C:/wampp/htdocs/drupal7_main
mklink /D drupal7_sub2 C:/wampp/htdocs/drupal7_main

Executing this will already give you a result when visiting localhost/drupal7_sub1. If everything went well, you should see your localhost/drupal7_main website.

Because your working with a localhost URL (and not real domain name, can be a development URL only existing on local, i.e. dev.yourproject.com), you need to slightly adapt your folder structure in order that each subwebsite uses its own settings.php and file folder for the files (uploads, css, ctools, js).

You need to prefix your subfolders under drupal7_main/sites/ with localhost.

drupal7_main/sites/drupal7_sub1 --> drupal7_main/sites/localhost.drupal7_sub1
drupal7_main/sites/drupal7_sub2 --> drupal7_main/sites/localhost.drupal7_sub2


Creating nodes with cURL that have multiple tags and a content moderation transition I've enabled the rest restui serialization hal and basic_auth modules and enabled and configured the Content resource like this:

I'm able to create nodes with:

X_CSRF_TOKEN=$(curl http://d8.local.org/session/token)
curl --include \
--request POST \
--user test:"test" \
--header 'Content-type: application/hal+json' \
--header "X-CSRF-Token: $X_CSRF_TOKEN" \
--insecure \
--data-binary '{"_links":{"type":
{"href":"http://d8.local.org/rest/type/node/article"}},
"title":[{"value":"Test"}],
"body":[{"value":"Body text."}],
"field_tags":[{"target_id":1}],
"type":[{"target_id":"article"}]}' \
http://d8.local.org/entity/node?_format=hal_json

How do I add multiple terms to field_tags? Every combination I try, like

"field_tags":[{"target_id":1,2,3}],

returns a 400 Bad Request

Also, how do I add a content moderation transition to the new node?

You need to map target_id => [id] as key/value pairs:

"field_tags":[{"target_id":"1"},{"target_id":"2"},{"target_id":"3"}]


How to load data from db with ajax? I am new to ajax so my question might be a basic one, but I have not found an answer anywhere so I ask here.
I am building eshop website on D7 with Commerce. On page where products are displayed I have 2 custom php scripts included - one that echoes menu(filter) and one that echoes products. The menu is implemented as a filter, users can select multiple checkboxes to display multiple categories of products. These categories are passed in URL, for example /eshop?filter=category1+category2. There are about 20 products in each category, but because user can select a lot of categories, there can be quite a lot of products to fetch from db and the page load is slow. So I would like to ajaxify this process so the behavior is like this: display whole page, including menu. Display loading gif for each category while it is fetched from the database. When data are ready, display the category(replace loading gif) and continue with the next category, until all categories are displayed.
function loadCategory(filter){

if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
            document.getElementById(filter).innerHTML = xmlhttp.responseText;

        }
    }
    xmlhttp.open("GET","my_php_file.php?filter="+filter,true);
    xmlhttp.send(null);
}

I am calling the above function(taken from w3schools) on jQuery(document).ready() event multiple times for each category(filter) and it works fine. The problem is that in my_php_file.php I need to have access to drupal functions - not only db_query(), but also some commerce functions since I am building custom add to cart forms. I have tried bootstraping drupal as hinted here, but it does not work as drupal shows site telling me that drupal is already installed.
How do I achieve this? Or am I taking wrong approach? Thanks a lot.

I suppose your list is implemented with views (if not you can easily do this), to load a view via Ajax use the following code; I supposed your view's name is VIEW_NAME and it's display machine name is block_0 and there is a contextual filter to get filter

$.ajax({
    url: Drupal.settings.basePath + 'views/ajax',
    type: 'POST',
    dataType: 'json',
    data: 'view_name=VIEW_NAME&view_display_id=block_0&view_args='+filter,
    success: function(response) {
        var output = response[1].data;
        $("#filter").html(output);
    },
   error: function(data) {
        alert('An error occured!');
    }
});

The Ajax call in Drupal framework is different to the one you usually see on non-Drupal websites.


drupal_alter() ignores more complex function names when the hook is called I have a module named wlm that calls drupal_alter() as follows.

drupal_alter('abc', $ref, $arg1, $arg2);

This works perfectly for a function like the following.

function wlm_abc_alter(&$ref, $arg1, $arg2) { };

However, it breaks/does nothing if the function is similar to the following one.

function wlm_this_is_some_extra_detritus_abc_alter(&$ref, $arg1, $arg2) { };

I want to be able to call this alter function several times within my wlm module, but because the naming convention seems to be limited to module_hook_alter() I can only use it once, which is less than desirable. Is this an intentional design pattern; or is it a mistake; or am I just missing something obvious?

Is it possible to do something like the following, where $my_func_name is delivered dynamically?

drupal_alter($my_func_name . '_abc', $ref, $arg1, $arg2);

It's intentional - a module should only be able to implement a single hook once, and the naming convention requires that the function be called modulename_hookname_alter(). Drupal isn't ignoring your more-verbose function name, but since it doesn't match the name of the hook, it's never going to call it.

You can create other hooks though, based on whatever makes sense to your use case. For example if your module had a bunch of contexts you might create hook_abc_CONTEXT_alter(), and invoke it like so

foreach (mymodule_contexts() as $context_name) {
  $hook_name = 'abc_' . $context_name;
  drupal_alter($hook_name, $ref, $arg1, $arg2);
}

But I think that's as close as Drupal core will let you get to the pattern you're trying to implement.


Custom URL on link to node I've got a field (URL) which contains a custom external URL for each node.
My goal is to set this custom url as link on the title which is displayed in a View. This is currently linked to a detail page (mydomain/node/5).

Unfortunately, I can't get it to work. How can I solve this?

You can set the node title as a token on the link-field (in the content type field settings).

You can alternatively output the field in the view as url plain text and rewrite the title to display as a link with the given field link as URL.


Alternative theming for subdomain I would like a different set of twig templates be used for all content that exists on a sub-domain of a website regardless of content type.

eg:

mysite.com/article (Main site theme)
sub.mysite.com/article (New templates)

Is there any way to do this?

You could add the domain to the template names in a theme name suggestion hook for each template, but if you want to have a complete set of twig templates for each domain it might be easier to create separate themes and switch them. In custom code with a theme negotiator or with this module Domain Theme Switch.


Are views cached through the core caching mechanisms or should I be setting the caching directly in each view? I see there are cache settings in each of my views. Do I need to set these or does the core caching mechanisms in /admin/config/development/performance automatically do some of this and these "extra settings" in views are if I want to override the default caching behavior of drupal core?

WHAT: Core performance caching stores and serves the whole rendered page with a cache id of the URL. Views caching goes beyond this to cache just the view output.

WHY: It's great for logged in users; other blocks on the page may be more dynamic but the view doesn't have to run a query every time for every user... just the occasional user who generates the page cache upon cache lifetime expire.

SETTINGS: Allowing the "rendered output" to be fresher than the query is useful for things like marking content as new, otherwise just match them up.

BIG PICTURE: Drupal serves page dynamically, using a server to build pages in PHP and access a database (or in-memory cache). This allows awesome features and content editor velocity... but the trade off is needing to understanding caching and do it right.

MODULES!

There's also a lovely Views Content Cache module which clears views cache on content edit. If you want to go further you may want to check out Cache Actions as well, I'd recommend Rules to fine tune this.

Additionally, Blockcache Alter allows you to set "per role", page, user, etc. caching options for each block on your site.

You can also add Page manager and Panels. This allows you to do interesting things like setting the cache "per user", "per role", or a number of other very useful configurations. Though I personally avoid panels.

DOCUMENTATION: For caching and performance in general check out the Drupal.org page.


Need help styling a field in a view I am using D7 and subtheming the commerce kickstart theme.

There is a view named Collection Products. I have added a field to the view called Product category: Description (indexed) that pulls in the taxonomy term description and places it above the product list. You can see the page here: http://freelance-graphic-designer.us/barmaiddev2/product-category/commercial-juicers

When it pulls this taxonomy term, all styling from the original content is lost. You can see how it comes in as one big block as h3. I have tried wrapping it in div containers in the wysiwyg editor on the original content page, but they just don't stay with it when it is pulled in by the view.

I have tried to style it within the view style settings with no luck.

I would like style the headings and body copy in my css style sheet and make it look more like the same content on its node here http://freelance-graphic-designer.us/barmaiddev2/commercial-juicers

Any suggestions? I am in a desperate hurry.

How I edited the Collection Products view

I needed to get rid of the  surrounding the field. Did so by editing the view template file:

Copied the file views-view-list.tpl.php to a Template folder inside my theme folder and renamed it views-view-list--collection-products--page.tpl.php

Removed the  around

See these sources on view templates:

http://drupal.org/node/352970

http://www.templatezine.com/2010/03/views-styles-and-theming-how-to-redefine-html-output/

In the View:

I added the field Taxonomy term: Rendered Taxonomy term
    Check "Exclude from display"
    View mode "Taxonomy Term Page"

Under Format > Settings
    Made Taxonomy term: Rendered Taxonomy term a Grouping Field

I also removed the header from the view since I had an image in the Rendered Taxonomy Term.

I also removed the 2 Taxonomy Term Name fields since the name came in with the Rendered Taxonomy Term.


How to add content programmatically to a field collection that it's in an entity (build with eck) I'm trying to save information into an entity build with eck, this entity has a field_collection with more fields.

I have take a look around internet, and I only find examples that works with node entity and user entity, but when I try to use the same code with my entity, it doesn't works.

This is my code:

<?php
$idform = 1;
$entity = entity_load('formulario',array($idform));
//dpm($entity);

$newfield_collection = entity_create('field_collection_item', array('field_name' => 'field_form_field'));
$newfield_collection->setHostEntity('formulario',$entity);
$newfield_collection->field_name[LANGUAGE_NONE][0]='name3';
$newfield_collection->field_form_id[LANGUAGE_NONE]['0']['value']=3;
$newfield_collection->field_sff_name[LANGUAGE_NONE]['0']['value'] = 'value name 3';
$newfield_collection->field_field_id[LANGUAGE_NONE]['0']['value'] = '13434';
$newfield_collection->field_field_type[LANGUAGE_NONE]['0']['value'] = 'value type 3';
$newfield_collection->save(FALSE);

?>

And this is my error message:

  EntityMalformedException: Missing bundle property on entity of type
  formulario. in entity_extract_ids() (line 7633 of
  /home/oscar/webapps/www/drupal/drupal7/includes/common.inc).

I have debuging the code and seems that the problem is with setHostEntity But I don't know if it's because I build the entity with eck module.

Thanks

Oskar

The problem here is that entity_load returns an array, not the single entity. So you should do something like this :

$entities = entity_load('formulario',array($id));
$entity = end($entities);

and then the rest of your code ...


Language fallback stack I have 4 language versions on my website.
Is there a way to define a language fallback order?

For example, if I'm on a node page and the language is set to English and there's no English translation I'd like Drupal to look for French, then German, then Spanish translation.

If you have language fallback enabled, then the fallback order is the order of the languages you have set at admin/config/regional/language


How to get url path info into a form variable I am creating a module for Drupal 7 that has form that will appear in a block. What I would like to do is get the url for the page that the block appears on (when displayed to the user) and store it in a hidden variable so that it can be processed later. Is this possible and how would you go about doing it?

Thanks

How to store the data depends on what you want to achieve with that data or how you want to process it afterwards. The easiest solution for that is probably using watchdog() after form submission:

watchdog('myblock', $url);

To get the current path there is current_path():

$url=current_path();

Please beware that you must disable caching for that block to have the code in your block processed all the time. Here is an answer on how to create a block programmatically in Drupal.


Create a block with articles from the current edition Hello I need to create a block that when is on the article page to show all the related content from the edition it belongs.

I tried with views but the problems comes from the fact I cannot add a filter of the current edition.

I think this should be done within a module but I needs some clues. Thanks.

I presume you categorize your content using taxonomy terms, or?
So, as an example, you create an article for issue number '122' and you 'could' use this in the url of your article, such as www.example.com/articles/issue_number/node_id

In this example, if the node id was 12345, the full url would look like this:

www.example.com/articles/122/12345

Now you could use views and arguments - in Views 3 'Arguments' was renamed to 'Contextual filters'.
So,

Create a view -> create block -> unformatted list -> titles (linked)
add a Contextual filter
Content -> Has taxonomy term ID
When the filter value is NOT in the URL: -> Provide default value ->
Type: Taxonomy Term ID from URL -> Load default filter from node page, that's good for related taxonomy blocks.
Check the boxes of the taxonomies you want involved here
skip to point 11

------------ old way -------

Provide default argument -> php code

$node = node_load(arg(1));
if($node) {
//Be sure to rename ->field_taxonomy_name to your field name
foreach($node->field_taxonomy_name[LANGUAGE_NONE] as $term) { $terms[] = $term['tid']; }
 return implode('+',$terms);
} else { return; }

Allow multiple terms per argument -> yes
Reduce duplicates -> yes

^^----------- old way ---------^^

Create a second argument to remove the currently displayed node from related content block
so, add a 2nd Contextual filter
Select Node: Nid
Action to take if argument is not present -> Provide default argument
Default argument type -> Node ID from URL
Exclude the argument -> yes
Save
Add block to node pages, only display in articles/*


Webform Custom-Field Module and validation I am currently working on a Webform that is used to enter some rather complex finance information (think tables with sums and other weird checks).

Since the styling has to be rather specific for this form I decided to create a custom Module that provides a new Webform-Component using the Webform Module Hooks.

That means that I created the HTML and WebForm Structure of the form using the _webform_render_component hook by providing a custom #process function that expands the initial component array to include a bunch of textfields and some custom themes.

function _webform_render_ff_promotion($component, $value = NULL, $filter = TRUE) {
  $element = array(
    '#weight' => $component['weight'],
    '#pre_render' => array('webform_ff_promotion_form_prerender'),
    '#webform_component' => $component,
    '#theme' => 'webform_display_ff_promotion_form',
    '#process' => array('webform_process_ff_promotion_form_expand'),
    '#prefix' => '<div>',
    '#suffix' => '</div>',
  );
  return $element;
}

And the custom process expansion:

function webform_process_ff_promotion_form_expand($element) {
  $element['general_group'] = array(
    '#type' => 'fieldset',
    '#theme' => 'ff_general_group_fieldset'
  );
  $element['general_group']['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#required' => true
  );
....
}

So far that works well and I have the form set up to look and behave as I need it to (saving etc works). Only problem now is validation - I cannot specify any other validations rather than required through the form_api.

I am trying to do this with the Webform Validation Module following this guide.
This works and I could now write a really huge list of if (is_numeric(...)) checks to see if the user did only enter numeric values to my textfields - but it feels kind of pointless.

So the main question here being - is there a best practice for custom components that rely on standard components internally (The whole custom component consists of just a bunch of '#type' => 'textfield' elements) to validate without writing a completely custom validator for it?

The Webform Validation Module feels like the wrong tool as it allows the validations to be done by the user in the admin. I'd rather just add more attributes like the  '#required' in the FormAPI and have them be checked.

Any help would be greatly appreciated - thanks!

Version Info:

Drupal 7.34
Webform: 7.x-4.6
Webform-Validation: 7.x-1.9

It looks like the hook _webform_action_set_component might be used for validation: "Setting the form element allows form validation functions to see the value that webform has set for the given component."

http://www.rit.edu/drupal/api/drupal/sites!all!modules!webform!webform.api.php/function/_webform_action_set_component/7.41


Is there an OOP alternative to hook_entity_operations_alter() in Drupal 8 In my custom module, I want to add a new action to the operations menu for each row of the user list that is displayed when going to /admin/people. I would like to stay in OOP-land and therefore I'm wondering if there is an alternative to implementing hook_entity_operations_alter() in my module? E.g. something that would allow me to create a PHP class for adding my action, or alternatively some way to add the action through the admin interface.

currently I have this code in somemodule.module:

/**
 * Implements hook_entity_operation_alter()
 */
function somemodule_entity_operation_alter(array &$operations, EntityInterface $entity) {
  if($entity instanceof UserInterface){
    $operations['translate']['title'] = t('Hello @entity_type', array(
      '@entity_type' => $entity->getEntityTypeId(),
    ));
    $operations['translate']['weight'] = 99;
  }
}

This works, but as said I would like an alternative that would skip the .module file completely.

The operations originally come from UserListBuilder. You can extend this class and alter User entity info to point list builder property to your class. The problem is that you need to implement hook_entity_type_alter wich is not in OOP land :-).

I suggest you keep this hook until Drupal become a true OOP application.

This article contains a quck comarision of hooks vs OOP events.


How to use theme_hook_suggestions() I'm on page of my website and I'm viewing it with the theme developer module, which gives me a lot of information. It gives me some theme suggestions based on theme_hook_suggestions() which are:

html__profile_personal
html__profile_personal__%
html__profile_personal__113
html__profile_personal__edit

How can I create a new theme for this page?  What naming convention should I use, given the info above?

Replace the underscore with a hyphen, and you get the name for the template file.

If the suggestions you are getting are the ones reported by theme_get_suggestions(), then they are the ones returned from template_preprocess_html() for a page at /profile_personal/113/edit.

The first suggestion would be applied for all the pages with a path starting with /profile_personal/; the last suggestion would be applied also for a page with path /profile_personal/edit, and the one before the last would be applied also for /profile_personal/113/revisions.

Whichever you choose, you should always check the path of the currently show page, via arg().


How do I add a field to a view that shows the user that published the node? I am using Drupal 6.22 and the module Revisioning to create an approval process for the creation of new nodes. An "Author" user role can create the initial draft of the content and the "Moderator" user role must sign in to review and approve. Once a Moderator approves the content, they may publish it.

Revisioning does not allow an easy mechanism to display the particular user (of user role "Moderator") that published the content. According to this issue, the maintainer of the module will not build that feature: http://drupal.org/node/611586

I am attempting to create this feature myself. I have installed and configured the Workflow module, as referenced in the thread above. Each node now has a "Workflow" tab that shows the history of the Workflow states and it is possible there to see the username of the user that published the node (along with all other state changes, which my client does not care about). I have not been able to find a way to pull this information into a View field in order to display it in a View.

Is this possible?

I am happy to provide any additional information that may be useful in providing a solution. Thanks!

You may want to have a look at the revisioning_content_summary view which comes with the Revisioning module. You'll find it at admin/build/views/edit/revisioning_content_summary.

It lists both the User: Name for the author and the Node: Last edited by for the moderator -- the information used in the Revisions tab, too.

Additionaly, have a look at creating views of type Node revision, which enable you to list all revisions of nodes, along with the revisioning information.


Divide a webfrom textfield component into a specific input format I have a need to divide a webform component into a specific formatting that is to match a coupon format. The user input needs to look something like this.

Then within the webfrom exported data the coupon needs to be displayed as one field.

Can anyone please suggest how this can be done or what the best practice is to achieve this within Drupal 7?

Thank you  - your help is much appreciated.

You can use jQuery masked input plugin to mask the field input.
If you really want to have 3 separate fields, you can do that with JS again. Have one field (let's call it "main" field) where you will save the value and generate the other 3 on the fly. Hide main field and on change update the value by adding the values of those three fields.


How to add a custom read more link in views? I have used views to create a page to look like the below screen shot. I have used trim to limit the description of the body to 200 texts. I have added "Link" and have termed it as "Read more". Is it possible to change the "Link" text in our webshop as "to shop"? I want this change to happen only for that specific item. For the rest it should be "Read more"

Probably going about it the wrong way, you could either set a custom text field on your node called 'Link text' then output that as a field and check 'Link this field to its node' in views.

Or you could use the 'Link' field type contrib module, then output that as a field, this will allow you to set custom text as the link label, but you will also need to supply the link itself. But this will allow more flexibility.


How to remove square brackets from name attribute in webform elements? Name attribute in rendered webform elements contain square brackets like submitted[field_machine_name].

.

Is there a way to replace square brackets in the name, so the name attribute looks something like "field_machine_name", without breaking the webform submission handler?

you can use hook_form_alter

Example D8

function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  if ($form_id=='comment_comment_form') {

    $form['subject']['widget']['0']['value']['#name'] = 'field_machine_name';

  }

}

Example D7

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

 if ($form_id=='comment_node_article_form')        {
    $form['subject']['#name'] = 'field_machine_name';
 }

}


Getting "Page Not Found" After Enabling the Devel Module Drupal 7 I'm trying to install the Theme Developer which requires the Devel module.

I've downloaded the Devel module via the Install new Module page in Drupal. When I enable the module however, I get redirected to a "Page Not Found" error.

Going to Reports > Recent log messages shows:

page not found  06/14/2017 - 10:23  modules/statistics/statistics.php
page not found  06/14/2017 - 10:23  modules/statistics/statistics.php
php 06/14/2017 - 10:22  User warning: The following module has moved within...
php 06/14/2017 - 10:22  User warning: The following module has moved within...
php 06/14/2017 - 10:22  User warning: The following module has moved within...

The three PHP messages complain that devel_node_access, devel, and devel_generate have all been moved.

Could this be some form of permission issue?

Edit:
I just tried again, but this time used a different theme. Devel was still not enabled, but I was redirected to a different page; /q=admin/modules&filter=devel&enabled=1&disabled=1&required=1&unavailable=1. Now I can't view any of my site. I rebooted my VM but my site is still unresponsive. Looks like enabling Devel has broken my site somehow.

Edit 2:
Destroyed and rebuilt my VM. This time I did not change the theme to my custom theme, and instead left the default theme enabled. I refreshed all caches, and attempted to enable Devel (I didn't have to re-download anything since the modules were still in my VM directory). This time it worked! Devel is now enabled. I'm not going to write an answer to this until I know exactly what changed and why it's now working fine.

Edit 3:
After enabling Devel, SimpleHTMLDom Api, and Theme Developer, I now see the following error on any of my pages.

the theme developer module has not been touched in years and it is unsupported. You should not expect it to work at all and it is certainly plausible that it will have detrimental effects on your site.

Unfortunately I suspect that you are out of luck unless you want to dig into the code yourself and attempt to get the module into a working state that does not blow up your site.


Why is my webform not displaying? I have a webform. If I go into the backend "content management => content" area and click "edit" for the form and then "preview", the form preview displays fine.

However, if I view that same webform on the frontend, I see either:

"Published by admin on Tue, 07/19/2011 - 15:15" if I am logged in as a new user
"Published by admin..." and in my $messages "You have already submitted this form. View your previous submissions." if I am logged in as a user who has submitted the form before.

This form was displaying fine at some point. Obviously someone working on the project (quite likely me) has broken it since then.

The form is published. The submission limit is set to "unlimited". The "status of this form" is set to "open". The "submission access" settings allow any "authenticated user" to submit the form.

What are some reasons for why my form might not be displaying? Do I need to add something in my page.tpl.php to have it display? What's the quickest way for me to debug this?

This sounds like something you could have done in the node template in your theme. You can try to change your theme. If that fixes then your theme is the root cause.


Prevent password reset urls from being redirected at login I'm using the following code to redirect users at login (Drupal 6):

function hook_user($op, &$edit, &$account, $category = NULL) {
switch ($op) {
    case 'login':
        if (_cns_user($account)) {
            unset($_GET['destination']);
            unset($_REQUEST['destination']);
            drupal_goto('user/'. $account->uid .'/training', NULL, 'steps');
        }
        break;
    }
}

The problem I have is that this doesn't allow for users to be redirected to the password reset page (user/reset/) when needed. Is there a way to prevent the reset url from being redirected? Thanks in advance.

The simplest way would probably be to just test for the path, which you can get access to via arg(). Something like this would do the trick:

function hook_user($op, &$edit, &$account, $category = NULL) {
  switch ($op) {
    case 'login':
      if (_cns_user($account) && !(arg(0) == 'user' && arg(1) == 'reset')) {
        unset($_GET['destination']);
        unset($_REQUEST['destination']);
        drupal_goto('user/'. $account->uid .'/training', NULL, 'steps');
      }
      break;
  }
}


TinyMCE editor does not show buttons in bar I need a WYSIWYG editor so I installed drupal wysiwyg module in sites/all/modules folder. Further I downloaded TinyMCE and installed it in sites/all/libraries/tinymce.

The editor configuration is correctly displayed in admin/settings/wysiwyg/profile/2/edit. My interface language is German and TinyMCE has this language pack installed.

When I go to edit some text in the backend the editor itself is initialized but no buttons are displayed.

Any ideas why there are no buttons and how do I fix this?

Did you enable some button /admin/config/content/wysiwyg/profile/yourprofile/edit ?

If yes, this can be caused by a javascript error. Do you see one in Firebug ?


Running an "is all of" filter on a field collection I'm currently working with a field collection lets call it Certificates. Certificates contains the following fields... Certificate Type, Certificate Number, Expiration Date, Etc.
I have a content type called Applicant that contains the field collection Certificates. Ideally, I'm trying create a view that allows for a "is all of" filter for the various certificates. We are trying to filter candidates by multiple certificates at the same time. To complicate this further, I've been asked to do this in a single multiselect drop down using chosen. By adding the field-collection as a relationship, I am able to add a Chosen multiselect that works correctly with the "is one of" operator, but it won't work with the "is all of". I think that the reason for this is that it seems like the certificate type is overriding the actual field-collection in order to display the certificate. Looking for suggestions. Any help will be greatly appreciated!!!!

I have a solution that's a bit of a work around, but seems to work fine. I ended up using the same relationship multiple times and increasing the delta value by 1 with each new relationship which pulled in each option in the subcategory (think first field in the field collection). I then grouped the fields and used a combine filter to run the "is all of" search. Seems to work great and isn't overly resource intensive. This will give you a 1 to 1 result based on whatever is in the the field collection field item you build the relationship off of.

Hope this helps.

Best,
Shawn


How to add multiple items to cart? I came across this other question and wondered whether it was compatible with Drupal 6/UC 2:  Add multiple items to cart

I would like to create a page that shows the thumbnail and title of all products in a category, with a checkbox next to each one. Then, when a shopper checks three, four, five products and clicks "add to cart", those products are all added to the cart.

Or... even better would be if the product automatically gets added to the cart when they click the checkbox, and they can then click a link to go to the cart and finalize their order after they have added all of the products they want... but I know that may be asking a bit too much. ;)

I'm thinking it would be nice for the mobile environment too... the phone/tablet user could simply tap-tap-tap the products they want and then proceed to their cart.

Can anyone point me in the right direction for this?

For a list with checkboxes I suggest looking at this issue about using Views Bulk Operations.


How to use User Points to buy/sell a custom content type? I'm currently working on an educational project as a sort of final keystone project for my major in undergrad. The project is a online artwork trading game, in which students take on the role of being an art dealer/collector, and buy, sell, trade, and advertise artworks to each other on the site. I chose to use Drupal as a CMS due to its flexibility, but relative user-friendliness, as I won't be maintaining the project after my graduation in a few weeks.

I've polished off most of the site's features, with the exception of one, the currency system. At the moment, I have used the User Points module to create a virtual currency (guilders) for students to use when trading their artworks. I have also created the artworks as a custom content type. I am trying to make it so that students can buy/sell or just straight trade artworks between each other. I've attempted to install the Drupal Commerce module and pursue that route, which doesn't seem to be working. I've also tried making it so that students can manipulate node ownership, but it looked like that would create a permissions nightmare eventually, leaving me at a loss as of what to do. Due to the fact I won't be around to maintain the site, my original question of module recommendations really more is a recommendation of a solution that's not overly technical, and is fairly stable. My professor (who is an Art Historian) will be maintaining the project, and while he has taken an introductory computer science course, an astute programmer he is not.

TL;DR: I need a way for users to use userpoints to buy/sell a custom content type between themselves, and I need to keep the solution as stable as possible due to long-term maintenance concerns.

Use the integration between the User Points module and the Rules module to create some custom rules to transfer user points from one account to another.

As a sample, have a look at this rule, which is used in combination with voting of a node, whereas the author looses "-2" points, and the voter looses "-1" points:

{ "rules_votedown_question" : {
    "LABEL" : "votedown_question",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "-1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Issue downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteIssued",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

If you simply adapt the amount of points (-2 and -1) to something like (eg) +25 and -25, you've a prototype to transfer (25) user points from one user to another.

If you replace the Rules event by an event like "something is flagged" (created with the Flag module), a simple click could be used to indicate "I want to transfer 25 user points of mine to this user). You could take this even a step further: since flags are fieldable, you could add a field to indicate the amount of points to be "moved".

The above Rules example may need further refinements, e.g. if you want to ensure that after moving points van User A to User B, the remaining points for User A is not negative. Refer to "How to check whether one's current User Points are negative with the Rules module?" for details about how you can implement such refinement also.

PS: I'm assuming this question is about D7.


How to combine Views, Rules and EVA to record submission? I have a Drupal 7 site and I'm using Views, Rules and EVA.

I have a specific requirement that I am sure can be achieved with the modules, but I am having no joy configuring a working process.

I have an 'Application' content type, which has a submission form embedded (i.e. visitor completes submission form for the role they are applying for).

As all visitors login in order to submit an application, I would like to record each application they make into a 'My Applications' view/block, within their User (/user) page.

I see the process as something along the lines of:

Visitor completes application form and clicks a Submit button.
Via Rules, an association/reference between the user and the specific role/application is recorded.
Using EVA, a custom view will list the applications the user has made (showing only his/her applications, unless admin).

The part I am failing with is how to configure a Rule, triggered by the submit button, that links the user to the specific application, in such a way that it can then form the EVA view.

Has anybody implemented a similar process? Recording applications (for jobs, events, meetings etc) and allowing users to see those they have applied for must be possible?

I would be happy to use an entirely different approach if there is a better method vs. the  Views/Rules/EVA idea.

Suggestions gratefully received. Thank you.

I am not familiar with EVA but it looks pretty good.

I have a similar use case with entityform.

You can embed entityforms on nodes using the entityreference field.

Now entityform comes with a view already set up that displays a user's latest entityforms.

Here is a screencap of the view configuration - it displays a user's latest form submission(s).

You can then add a 'block' version of this view (the 'add' button in the top left corner.)

You can then configure your new block to only show up on the logged-in-user's /user page.

Hope that helps. Incidentally let me know if you are trying to get the form-fields to be pre-populated with user details.

Based on your comments:


Override image-formatter.html.twig I'm looking for an option to override the image-formatter.html.twig template in my own theme. But in the HTML page output (twig debug is set to true) there's no option listed to override the formatter template. The only thing I see is:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'image_formatter' -->
<!-- BEGIN OUTPUT from 'core/modules/image/templates/image-formatter.html.twig' -->

I need to place a rel attribute for the link which surrounds the image.

I found a solution which uses the option that you can write your own field formatter in your own module. But that seems to be too complex for this simple task.

In your .theme file, add this suggestions alter hook (and flush caches so the new hook definition is picked up):

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_image_formatter_alter(array &$suggestions, array $variables) {
  $entity = $variables['item']->getEntity();
  $field_name = $variables['item']->getParent()->getName();
  $suggestions[] = 'image_formatter__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name;
}

Then if you look at the twig_debug output, you should see something like:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'image_formatter' -->
<!-- FILE NAME SUGGESTIONS:
   * image-formatter--node--article--field-image.html.twig
   x image-formatter.html.twig
-->

Once that is done, you can create your template file called image-formatter--node--article--field-image.html.twig in the templates directory of your theme, flush caches again so the template is picked up, and override the template with any changes you'd like.

This should include a caveat that the code hasn't been thoroughly tested :)


A node reference is empty, although the multilingual support is enabled, and the node is translated I just created a multilingual site (English-French) using Drupal 7 with the module Internationalization 7.x-1.4.
Everything is working fine except with the module References 7.x-2.0. For instance, I created a content type "School" so that each user is affiliated to a school (User A --> School 1, User B --> School 2, etc.), meaning I simply added a node reference to "School" in the user account settings. But here is the problem: if a user chooses a school on the English version of the site it won't remember the school choice on the French version (the node reference becomes empty) and vice versa.

How do I solve this?

I did enable the multilingual support for "School" with translation.

Have a look at this.

http://www.ostraining.com/blog/drupal/multi-lingual-drupal/


How can I "outsmart" caching? A view returns an event, which occurs on the current day, in a block.
If there is no current event in the database (empty result), a second view is started, which then outputs events from the past.

It is working, when I am logged in. As long as I am logged in, I see correct results, even in the view preview.

If I look at the next day as anonymous user, I don't see the current event; the block displays the view result of the previous day.
Only with a registration attempt the output is updated, no matter whether I logged in, or a registration attempt is started.

In the views I have changed under -> ADVANCED -> cache: „tag based" to "time-based" with duration of 1 hour for query results and output format.

Unfortunately, the result is the same: the output block is not updated according to the new day.
Now I have deactivated the data caching of the view module, in the hope that tomorrow the display is now updated independently.

If this does not work, only to log in once the day to force an update?

Admin/performance:

Modules:

views/settings/advanced:

The View:

The View (extended)

The issue you have is with the module Internal Page Cache for anonymous users. You have several options:

If you want to serve for anonymous users a newly built page on each request the same way as for logged in users, then uninstall the Internal Page Cache module. The dynamic page cache will still cache pages, but does respect the cache contexts and max-age you set on the page elements.

Performance wise it is not a good idea to do this, so it might be better to configure a max-age for the Internal Page Cache, see this answer https://drupal.stackexchange.com/a/196557/47547, where you use an event subscriber to set an Expires time in the response.

If this is only for Views, another option is to modify the route definition of the view by setting a no_cache option, see this answer https://drupal.stackexchange.com/a/230242/47547

In all cases you need to configure /admin/config/development/performance for external caches like the browser cache.


How do I get the referring entity of a referenced node in a template file? I am struggling since a couple of days with my problem now and I have no idea what else I can do to come to a stage of enlightenment.

In Drupal 8 I have a content type called "Release" and a content type "Article" which, among others, contains Reviews of Releases. So in Releases I created an entity reference field called "Review" which references Article content type.

For index pages I could create views of Articles and there I pretty easy could integrate the fields of the referencing release entity via the Relations section in views administration. There the reverse direction of a relationship is not a problem.

How do I access the fields of the release in a node--article.html.twig template?

Edited due to character limitation in the comments section (I hope this is allowed):
Thank you so much, @JeremyM4an, but there was a little misunderstanding due to my bad explanation of the problem. I should have mentioned that article has a reference to a taxonomy term, called field_post_category.

So a review is an article with field_post_category == 'Review' and finally a release has an entity reference field, called field_review, referring to article. After reading your answer I tried this:

$category_field = $node->get('field_post_category');
$category_field = $category_field->getValue();
if( isset($category_field[0]['target_id']) && $category_field[0]['target_id'] ){
  $term = taxonomy_term_load($category_field[0]['target_id']);
  if($term && $term->get('name')->value == 'Reviews'){
    $release = \Drupal::entityQuery('node')
    ->condition('type', 'release')
    ->condition('field_review.entity:node.nid', $node->id())
    ->execute();
    // Load release node and store in variables.
    $variables['release'] = Node::load(array_values($release)[0]);
  }
}

But this does not work.

You can get the "relationships" to your referencing node in a preprocess function, in your theme's mytheme.theme file:

function mytheme_preprocess_node(&$variables) {
  if (!empty($variables['node'])) {
    $node = $variables['node'];
    if ($node->getType() === 'article') {

      // Get the review by article node id.
      $review = \Drupal::entityQuery('node')
        ->condition('type', 'review')
        ->condition('field_article', $node->id())
        ->execute();

      // Get release by review node id.
      $release = \Drupal::entityQuery('node')
        ->condition('type', 'release')
        ->condition('field_review', array_pop($review))
        ->execute();

      // Load release node and store in variables.
      $variables['release'] = Node::load(array_values($release)[0]);
    }
  }
}

Then you can access the fields in your template:

{{ release.field_name.value }}


Only allow 1 discount using commerce_discount I am having trouble finding out how to only allow 1 discount per order.

eg. a specific user role allows 15% discount on their order.
We also have another discount set up that applies a further 15% on a certain product.

We don't want to allow both discounts to be applied when that specific user role orders that product.

We are using:

Drupal 7
Commerce 7.x-1.13
Commerce_discount v 7.x-1.0-alpha5

Your version of Commerce Discount is too outdated to support discount compatibility. However, it's so old, that the upgrade process may be complicated. Drupal Commerce itself is also currently at version 1.15, so that will need to be updated, too.

I'd recommend creating a copy of your website and bringing those modules up to date, maybe even one version at a time, running update.php in between each upgrade. (Theoretically, it should work fine to run update.php all at once, but Commerce Discount has to do a lot of field manipulation in its update functions, and I just worry about the potential for things to break...)

Once you do that, you'll have discount compatibility settings that will allow you to enforce a discount being incompatible with any other discount, and by adjusting the sort order on the discounts you can identify which discounts should apply first to ensure the restricted one applies first when possible.


hook_view, hook_theme and Display suite My module adds further content to a specific node bundle, in the "view" phase, in the following way:

hook_view (under the right conditions) adds these "contents" to the node display array
hook_theme specifies how to render the possible render_array related to the added contents

I followed several tutorials about, and in effect the documentation (of the latter) reports:

  The structure of $node->content is a renderable array as expected by
  drupal_render().

Here is an abstract from my code:

/**
 * Implements hook_view().
 * Remember: hook prefix is based on the base of the node type (node-type-specific hook)
 */
function mynode_view($node, $view_mode) {
  $contentWrapper = entity_metadata_wrapper('node', $node);
  $myfield = $contentWrapper->myfield->value();
  if ($view_mode=="full") {
    $node->content["ds_column"] = array(
      '#markup' => theme('ds_column', array(
        'element' => _mymodule_to_render_arrays($myfield, $node->status),
        )),
      '#weight' => 150,
    );
  }
  return $node;
}

As you can see this adds the ds_column to my node content, telling me it has to be rendered by a theme function.
It also passes to the theme function a "render array" (containing the information to be rendered).

/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'ds_column' => array(
      // See http://drupal.org/node/224333#theme_changes
      'variables' => array('element' => NULL),
      'template' => 'theme/ds_column'
    ),
  );
  return $theme;
}

This part of my module explain what template file have to be used in order to properly render, in the node (bundle) page, the content I added by the previous hook.

For what I see this is the standard approach. And indeed everything works fine.

The problem description starts here.

The module I described has been installed on an environment using the Display Suite module to define how to show contents for each node type in the node page, but the Display Suite module doesn't allow to see, in the configuration page, the content I added with the code shown above. So now that content doesn't appear in the node page.

I would like just to see the "ds_column" in the Display Suite configuration page for that specific node, in order to place it properly.

I can't figure how to see it (have I to implement also a DS hook? Have I to modify my code in some way?). I just found the "Display Suite Extra" sub-module, but I wasn't able to solve by it.

For people interested to the solution, you have to use the hook_field_extra_field() hook.

There you can declare your own "virtual fields" and they will appear as fields also in the Display Suite.

To link them to the content you create, just be sure to use the same name as a key both in the field name and in what you add as a node->content.

To provide you with the solution related to my example:

/**
 * Implements hook_field_extra_fields().
 */
function mymodule_field_extra_fields() {
  $extra['node']['my_custom_bundle_type']['display'] = array(
      'ds_column' => array(
        'label' => t('My column'),
        'description' => t('Description is also mandatory'),
        'weight' => 99,
      ),
  );
  return $extra;
}

As you can see ther key ds_column is the same used in the mynode_view (or in any other function implementing a hook able to modify the content render array).


Drupal 8 - "Level up" link in taxonomy term view this is my first question on Drupal Answers so... nice to meet you :)

On Drupal 8 site I've replaced default taxonomy term page for one of my vocabularies with composition of view and block. View shows a table with nodes tagged with taxonomy term from the URL. Block contains a view with taxonomy term's children. These two components together have a feeling of files explorer application (like Finder, Explorer or Nautilus). But one thing is missing - a link to the parent taxonomy term. Name it "level up" or sth.
I've tried adding something to the footer of block's view but with no results. And didn't find anything on the internet. Do you know if there is any possibility of doing this?

PS: I know that there is breadcrumb on every page, but this is not what I'm looking for.

Personally I would just write a custom code:

You will need to define a custom block
And you will also need to get the parameter from the URL.
You will need the "database" service (select) in your code, to query the parent term (if there is any).


Setup links for pagination pages I have articles/?page=2, I need to make it like articles/page/2 or articles/page-2

How to do so?

The Clean Pagination module is enabled and on admin/config/system/cleanpage I added "articles".

articles?page=1 is the second page in the pagination link and it looks like in this screenshot:

The module changes the reference to articles/page/1, although it would be logical to do so also for articles/page/2.

How can it be implemented? What alternative methods are there?

The configuration is in Drupal itself. Just visit /admin/config/search/clean-urls and enable it :

Note : It needs to be enabled in Apache as well. In Apache rewrite module should be enabled.


Provide several download option for same image in Drupal 7 Would anybody have any idea of how to create several download option of the same image in Durpal 7.

The sample website is: http://www.travesto.com/content/101jpg-anime-animated where several download option is enabled.

I would like to create a similar option for my birthday photos. I think may be views module is used here. BUt not sure. If anybody have any idea of doing this. plz help me....

Do you mean different resolutions? Simply, you have to upload them, and link the files.

Then there are the following modules:

DownloadFile
Download


Print a specific field I am working on my template and have gotten it laid out almost how I want.

I have it print the content with {{ page.content }} but what I need is on another part of the page I want to print out a specific field from that same content.

I tried different combinations of twig tags but none worked for me.

{{ page.content.field_name }}
{{ content.field_name }}
{{ item.field_name }}
{{ field_name }}
and a few others

I tried googling but I didn't find anything.

Consult this, you will see there is a variable node that is fully loaded node object. so try the following. one of them should work

{{ node.field_name.value }}
{{ node.field_name }}
{{ content.field_name }}


how to get values from two content types using one entity reference I'm using Drupal 7 and have 3 content types -

Product
Purchase
Sales

In sales content type, I'm using entity reference I want to fetch and display "product name" from Product content type and "MRP" from Purchase content type. How can I achieve this by configuration?

If all 3 Content types need to be interrelated then it makes sense to use the same Entity Reference Field to connect them (two CTs both use the same Field to reference the third CT).

But this isn't a requirement, it just makes some things easier if using Views to display information from one CT node on related CT nodes. While this can be solved using Views there is an easier way.

Use Content view modes to control ER Field display

The easiest way to control which Fields from the referenced node an Entity reference Field should display is to use Content type Fields view modes (not related to Views module).

You can see available view modes on the Manage display page of a Content type, at the bottom under Custom display settings.

You need to enable an existing view mode or create a new one on your Product and Purchase Content types, so they can be used for ER Field on Sales CT.

Select the view mode you want to use (Manage display page) for this purpose and on Product CT hide all the Fields except the product name.

Similarly, on the Purchase CT view mode you selected for this purpose hide all the Fields except MRP.

Then on Sales CT Manage display page (I'm assuming you have two different ER Fields, one for each CT referenced) select Rendered entity as your ER Field Format for both Fields, and change its configuration to use the view mode you configured in previous steps.

This way when you visit a Sales node it will show product name and MRP Fields from the referenced nodes instead of their node titles.

Create new Content view modes in D7

You might need to create a new view mode for this purpose. In D7 it doesn't come out of the box (as it does in D8), but you can create new modes with the help of an additional module or a very simple custom module. Read all about it in this article: 3 Easy Ways to Create View Modes in Drupal 7.

Display information from another node

To display one node information on a different page (in your case you want to display MRP field from a Purchase node on Service pages) you can use Views module (this is different from view modes mentioned above).

You use Views to create a Block Display, filter out the node you need, and show only the MRP Field. The place that Block in a region in your theme (maybe Content region) and configure it so it shows only on Service CT nodes.

Create a new View of showing Content of type All, Create a Block of fields, showing 0 item (this means unlimited, for performance reasons)
Add a new Filter Content: Nid, keep the Operator Is equal to and enter your Purchase node ID number in the Value field (you can see the NID number on that node Edit page in the link)

If you have Views preview enabled you can now see that exact Purchase node title in the Preview results
Rearrange the Filters so that Content: Nid Filter is above the Content: Published (Yes) Filter (this is for performance reasons)
Remove the Content: Title from Fields
Add a new Field Content: MRP (or whatever that field is called in your case), configure how you want that Field to appear on Service nodes
Save the View and place your Block in a region of your theme, but limit it to show only on Service CT

To test it visit one Service node and see if the Purchase MRP is showing there, and if you visit any other page then it shouldn't show.


Create node using services I want to create a mobile application using my drupal application. For the communication I use the module services. The connection system works with success. This return this result.

    {
  "sessid": "98gnwpE1GeguxN1y4t0WkWhDzK-C-Ashbn5GExj9l7M",
  "session_name": "SESS7609adb25a00cf561a9d882a31e81d29",
  "token": "aK4L6D1APRH16lGSAirIaZVGR02T5gs8DeE5jffYCKI",
  "user": {
    "uid": "30",
    "name": "admin",
    "mail": "zinalacina@gmail.com",
    "theme": "",
    "signature": "",
    "signature_format": "filtered_html",
    "created": "1486745824",
    "access": "1487091377",
    "login": 1487154223,
    "status": "1",
    "timezone": "Africa/Ouagadougou",
    "language": "en",
    "picture": null,
    "init": "zinalacina@gmail.com",
    "data": {
      "ckeditor_default": "t",
      "ckeditor_show_toggle": "t",
      "ckeditor_width": "100%",
      "ckeditor_lang": "en",
      "ckeditor_auto_lang": "t",
      "contact": 1
    },
    "uuid": "14899bf3-1a0d-42b5-934e-650471d7da54",
    "roles": {
      "2": "authenticated user",
      "3": "administrator"
    },
    "rdf_mapping": {
      "rdftype": [
        "sioc:UserAccount"
      ],
      "name": {
        "predicates": [
          "foaf:name"
        ]
      },
      "homepage": {
        "predicates": [
          "foaf:page"
        ],
        "type": "rel"
      }
    }
  }
}

Now I want to create a node type article and I use this method

POST: http://localhost/drupal-7/?q=my_endpoint/node.json
{"type":"article","title":"BEVVtDcZmL","language":"und"}

But the result [
  "Access denied for user anonymous"
]. I know it normal because he don't know who wants to create the node.
Now I question is how to parse sessionId or token to have the permission to create my node? Thanks

First thing you need to do is login via Services (unless you allow anonymous users permission to create content), which is a POST call to ?q=[my-endpoint]/user/login.json
Once logged in, you need to retrieve a new CSRF token (this new token should be returned within the login result)
Then make a POST call to ?q=[my-endpoint]/node.json, sending along something like this:

-

{
  title: "Hello world",
  type: "article",
  uid: 123,
  body: {
    und: [
      { value: 'How are you?' }
    ]
  }
}

Attach an X-CSRF-Token header to the request using the new token value generated after logging in.

That should then return something like this to you:

{
  nid: 456,
  uri: /* ... */
}

I have a blog post with examples of most of the Services Resources here: http://tylerfrankenstein.com/code/drupal-services-examples


When is the available 'language: English French...' link displayed under translatable content? I am struggling with the i18n configuration of my site and the display of the available translated content 'languages' link displayed next/under the content.

Under which condition will this link be displayed for translated content?

The content type is translated-enabled
The language field must be displayed/visible in the content type configuration
There must be more than one language made available
The content must be translated
...?

I guess all the above apply, but is there more?

The reason I am asking this is because I believe I have configured my site properly, but I still don't see that link to jump between translated content. I am looking for a check list to find my error(s) or misunderstanding. Thanks.

I'm guessing this is your other question!

I'm not exactly sure but I just did this from scratch on my Drupal test site and found it to work.

Modules - The only module I have enabled is Multilingual content
Content Type - Edit - Publishing options - Enabled, with translation
Content Type - Edit - Multilingual settings - Nothing selected except 'Normal'
Regional and language - Languages - Multiple languages enabled
Regional and language - Multilingual settings - Node Options - Hide content translation links is not checked

i18n can definitely be uncooperative...


How do I create and use a custom hook? I posted a question here, which had one suggestion, but no answer. Does anyone have any advise on how to implement a custom hook in Drupal 8 which will allow other modules to update a table of contents which is created by a parent module? The table of contents will be an unordered list.

This section resides in a controller in the parent module:

$plugin_items = [];
// Call modules that implement the hook, and let them add items.
\Drupal::moduleHandler()->alter('flot_examples_toc', $plugin_items);
if (count($plugin_items > 0)) {
  $output['plugins'] = [
    '#title' => 'Plugins',
    '#theme' => 'item_list',
    '#items' => $plugin_items,
  ];
}

And this resides in the child [module].module file.

use Drupal\Core\Url;

function mymodule_flot_examples_toc_alter(&$item_list) {
  $options = [
    ':one' => Url::fromRoute('flot_spider_examples.example')->toString(),
  ];
  $item_list[] = t('Spider Chart (with spider plugin)', $options);
}

The parent creates an array and passes it to the children by reference. They can alter the array by adding elements to it. The parent then adds it to the render array.


Colorbox Iframe Resizing I am trying to resize an colorbox containing an iframe. The following code works fine on normal sites but in Drupal it is having problems. Can anyone suggest what I am doing wrong? The colorbox is supposed to resize to the size of the content plus a specified offset in the Resize function.

(function($) {
    $.fn.formToWizard = function(options) {
        options = $.extend({
            submitButton: ""
        }, options);

        //Resize the colorbox
        function Resize_Box(){
            var x = $("body").width();
            var y = $("body").height()+30;
            parent.$.fn.colorbox.resize({
                innerWidth: 600,
                innerHeight: y
            });
        }

        var element = this;

        var steps = $(element).find("fieldset");
        var count = steps.size();
        var submmitButtonName = "#" + options.submitButton;
        $(submmitButtonName).hide();

        // 2
        $(element).before("

");

        steps.each(function(i) {
            $(this).wrap("

");
            $(this).append("

");

            // 2
            var name = $(this).find("legend").html();
            $("#steps").append("

");

            if (i == 0) {
                createNextButton(i);
                selectStep(i);
            }
            else if (i == count - 1) {
                $("#step" + i).hide();
                createPrevButton(i);
                createNextButton(i);
            }
            else {
                $("#step" + i).hide();
                createPrevButton(i);
                createNextButton(i);
            }
            Resize_Box();
        });

        //Create the previous button
        function createPrevButton(i) {
            var stepName = "step" + i;
            $("#" + stepName + "commands").append("< Back");

            $("#" + stepName + "Prev").bind("click", function(e) {
                $("#" + stepName).hide();
                $("#step" + (i - 1)).show();
                $(submmitButtonName).hide();
                selectStep(i - 1);
                //Only resize if going back to the first step since it has fewer options
                if(i==1){
                    Resize_Box();
                }
            });
        }

        //Create the next button
        function createNextButton(i) {
            var stepName = "step" + i;
            if(i != count-1)
            {
                $("#" + stepName + "commands").append("Next >");
                $("#" + stepName + "Next").bind("click", function(e) {
                    var currentq = document.querySelector('div#step'+i+' input[type=radio]').name;
                    if($('input[name='+currentq+']:checked').length > 0) {
                        $("#" + stepName).hide();
                        $("#step" + (i + 1)).show();
                        if (i + 2 == count)
                            $(submmitButtonName).show();
                        selectStep(i + 1);
                        //Only resize if going from the first step since all other steps have more options
                        if(i == 0) {
                            Resize_Box();
                        }
                    }
                });
            } else {
                $("#" + stepName + "commands").append("<input id='SaveAccount' type='submit' value='Submit' class='next notvalid'/>");
            }
        }

        function selectStep(i) {
            $("#steps li").removeClass("current");
            $("#stepDesc" + i).addClass("current");
        }
    }
})(jQuery);

Try replacing $ with jQuery. By default I don't believe Drupal allows the $ as a shortcut due to potential compatibility issues with other libraries.