How do I make an ajax callback in Field Plugin formElement() reload form? I've created a custom field as a module Plugin and have the following code in the formElement() method of the field's Widget.php.  The intention is to populate options in the second select element based on the value chosen in the first element:

$element += array(
  'sheet_name' => [
    '#title' => 'Sheet',
    '#description' => 'Select the sheet',
    '#type' => 'select',
    '#options' => $options,
    '#required' => TRUE,
    '#element_validate' => [
      [$this, 'validate'],
    ],
    '#ajax' => [
      'event' => 'change',
      'callback' => [$this, 'getPositions'],
      'progress' => [
        'type' => 'throbber',
        'message' => 'Getting positions.',
        'method' => 'replace',
      ],
    ],
  ],
  'position' => [
    '#type' => 'select',
    '#options' =>['Select'],
    '#title' => 'Position',
    '#description' => 'Position',
    '#prefix' => '
',
    '#suffix' => '
',
  ],
);
return array('value' => $element);

My callback is as follows:

$options = ['Select' => 'Select'];
foreach ($positions as $position) {
  $options[$position['position']] = ucfirst($position['position']);
}

$sheet_position = [
  '#type' => 'select',
  '#options' => $options,
  '#title' => 'Position',
  '#required' => TRUE,
  '#description' => 'Position',
];

$response = new AjaxResponse();
$response->addCommand(new HtmlCommand('#position-select', $sheet_position));
$form_state->setRebuild(TRUE);
return $response;

This puts the option values I want into the second select element, but the form isn't being rebuilt, even with the call to $form_state->setRebuild(), so my updated select element isn't being associated with a form field.  I'd love to understand why, but I'll settle for any way to force the form to rebuild after the callback runs.

Update:  I have tried $form['position'] instead of $sheet_position in my callback but no joy there, either.

Here is what I did in TVI which does something similar to what you are doing (changing out options):

    // form code ...

$form['tvi']['view'] = [
  '#type' => 'select',
  '#title' => 'Using the view',
  '#description' => $this->t('The default view that you want to use for all vocabularies and terms.'),
  '#default_value' => $config->get('view'),
  '#options' => $view_options,
  '#states' => [
    'visible' => [
      ':input[name="enable_override"]' => array('checked' => true),
    ]
  ],
  '#ajax' => [
    'callback' => '::loadDisplayOptions',
    'event' => 'change',
    'wrapper' => 'tvi-settings-wrapper',
    'progress' => array(
      'type' => 'throbber',
    ),
  ],
];

// form code ...

  /**
   * Ajax callback - null the value and return the form.
   * The value gets nulled because we cannot overwrite #default_value in an ajax callback.
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @return mixed
   * @see https://www.drupal.org/node/1446510
   * @see https://www.drupal.org/node/752056
   */
  public function loadDisplayOptions(array &$form, FormStateInterface $form_state) {
    $form['tvi']['view_display']['#value'] = '';
    $form_state->setRebuild();
    return $form;
  }

In my form code, I am reading the values from $form_state and checking them - which is passed to a function that populates the option list. Therefore, when the AJAX callback rebuilds the form, the new option list will be populated.

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    $config = $this->config('tvi.global_settings');
    $views = Views::getEnabledViews();

$view_options = ['' => ' - Select a View -'];
$display_options = ['' => ' - Select a View Display -'];
$default_display = '';

foreach ($views as $view) {
  $view_options[$view->id()] = $view->label();
}

if (isset($values['view'])) {
  $display_options += $this->getViewDisplayOptions($values['view']);
}
elseif ($config !== NULL) {
  $view = $config->get('view');
  $view_display = $config->get('view_display');

  if (isset($view)) {
    $display_options += $this->getViewDisplayOptions($view);
  }

  if (isset($view_display)) {
    $default_display = $view_display;
  }
}

$form['#prefix'] = '
';
$form['#suffix'] = '
';

// irrelevant fields redacted...

$form['tvi']['view'] = [
  '#type' => 'select',
  '#title' => 'Using the view',
  '#description' => $this->t('The default view that you want to use for all vocabularies and terms.'),
  '#default_value' => $config->get('view'),
  '#options' => $view_options,
  '#states' => [
    'visible' => [
      ':input[name="enable_override"]' => array('checked' => true),
    ]
  ],
  '#ajax' => [
    'callback' => '::loadDisplayOptions',
    'event' => 'change',
    'wrapper' => 'tvi-settings-wrapper',
    'progress' => array(
      'type' => 'throbber',
    ),
  ],
];

$form['tvi']['view_display'] = [
  '#type' => 'select',
  '#title' => 'With this view display',
  '#description' => $this->t('The view display that you want to use from the selected view.'),
  '#default_value' => $default_display,
  '#options' => $display_options,
  '#states' => [
    'visible' => [
      ':input[name="enable_override"]' => array('checked' => true),
    ]
  ],
  '#prefix' => '
',
  '#suffix' => '
',
];

return parent::buildForm($form, $form_state);
}

(Sorry for the broken paste) So when the form rebuilds, the options are populated from another method, while the AJAX callback just triggers a rebuild.

As a side note, the reason I am setting #value to '' is to force the field to default to the placeholder 'Select a Value' on change. Otherwise, it will stick to the last selected position by the user.


Custom column in commerce view? I have a view that lists all the orders. I want an action/operations column in the view which has buttons/links for eg: edit, repeat, delete, upload, download, reset, print. I cannot find a way to include a custom column in my view.

Current "Operations links" Columns shows me some menus which are added by default. Can I change them or can i add another column with my own choice of buttons/links ?

You have two "simple" options and a third "hard" option, which involves writing a custom Views field ... I'm going to skip that one and focus on the simpler options.

Those links all share a common pattern with only the order ID changing based on the row you're looking at. You can use tokens ("replacement patterns") in custom text fields on Views, including the order ID if you've added it to the View's fields list. This means your first option is to add the Order ID field to the View (and hide it by "excluding it from display") and then add a custom text field that adds whatever HTML you want, using the order ID token in the URLs.
The other option would be to add custom CSS to the View that alters the dropbutton styling. In the default HTML for that operations column, it's just using CSS to turn multiple links into that dropbutton format. You can undo that with your own CSS if you'd like, using the classes on the individual links to pick the right icon or whatever from your theme (e.g. "edit", "delete", etc.).

Either one of these solutions will be much simpler than writing custom Views code, and the second doesn't involve editing the View at all. : )


Drupal installed in the web root but not at the base of the domain name If I was to have my site in the web root, for example /var/www/ but the path to my site is http://example.com/drupal, how do I configure the base path etc.

If I set my base path to http://example.com/drupal it doesn't seem to work unless the site is also in a subdirectory (ie. /var/www/drupal/).

I know I can easily just move the site to /var/www/drupal/, but I'm curious to know if it is possible to do it at /var/www/ with just drupal config.

It it impossible, unless you count .htaccess (or similar config file for your webserver) as Drupal config too. If you do, in Drupal UI change base URL to http://example.com/drupal and use mod_rewrite to remove "drupal" from URI before further processing.

Note that this will not disable direct access. Of course you can block any calls without "drupal" prefix, but it would mean nothing except Drupal can work there. So if your goal is anything more than marking it's Drupal in your URLs, it's not a way to go.

Note: your mileage may vary depending on web server used.


Use entity reference to target revisions of an an entity I'm building a custom entity document which supports revisions. Revisions are seen as versions of the document (v1.1, v1.2, ...), the title field is revisionable as well.
Then there is a custom entity customer, which needs to accept documents. On creation of a customer, I need to point out which revision of the document is suitable for this customer.
I have an entity reference field on the customer to target a document. However, I'm not achieving to target revisions of a document.
I tried entity reference display in views (with a view that supports revisions) but I'm not able to select it in the field settings (no eligible view found). Probably because I can only select 'Document' as target type and not 'Document revisions'.
I tried entity reference revisions module but gave me the same results. This module just keeps track of changes in parent vs child revisions (I guess).

I would expect document revisions being available in the settings above!

Any suggestions on how to do this properly, am I missing something? I want to make use of core as much as possible for this one.
Update: I ended up creating a custom field plugin to get the required solution.

Revisions are stored in a separate db table from content. Views module makes you choose the base table for the query to the database when you're creating a new View (it's commonly called Views type: Content, User, Media, Taxonomy terms).
The easiest way to allow an Entity Reference Field to choose a particular Revision of a Content item is to build the list of Content Revisions items, and not a list of Content items.
Create a new Views entirely but this time choose Content revisions under Show, and not Content (you can't change that from within your existing Content type Views).
Your aim it to have a separate revision in each Views row, because when you're using that list within an ER Field each Views row becomes one checkbox/radio button to select when you're creating a new node.
Revisions can be grouped by their original content ID, Title or something else in common, but I'm not sure if the Entity Reference Views Display type supports that, I expect it doesn't and it won't affect it, you'll still get a plain list of all Revisions and you need to make sure yourself what to output and how to style it to make the options clear. There are probably ways on how to improve the ER Display output in Field widgets but that is out of scope of this question.

I haven't tries this, but usually when listing content referenced through ERs you need to add a Relationship to get any other info than an ID of the referenced entity. You'd need a Relationship to get that info. In your case if you start with Content Views type I expect you'd have to make sure to have each Revision is in a separate row (after you make them appear in results by adding a Relationship, and you'd probably need to list only the Revision info to make them appear in separate rows). I know it's possible to create the reverse ER Views through the forward list Views this way, but haven't tried it with Revisons, maybe the same logic applies.
Anyway, go with the Content Revisions Views type as explained above ;)


Required fields in form not validated I am currently constructing a form using an Ajax handler. The problem is that since i used Ajax, the submitting part is run without returning any error message. It is only when I clear the cache that all the errors appear (and the form disappear).

function My_Modile_form($form, $form_state, $arg){
     //constructing the form with REQUIREDfields
  $form ['submit'] = array (
      '#type' => 'submit',
      '#ajax' => array (
          'callback' => 'mymodule_form_ajax_callback',
          'wrapper' => 'result-div'
      ),
      '#value' => t ( 'Lancer la simulation' ),
      '#weight' => 10000
  );
}

function My_Module_form_validate($form_id, $form) {

  $form_numbers = array (
      'field_one',
      'field_two'
  );
  foreach ( $form_numbers as $form_number ) {
    $numb = $form ['input'] [$form_number];
    if (! is_numeric ( $numb )) {
      form_set_error ( $form ['complete form'] [$form_number] ['#title'], 'ERROR !' );
    }
  }
}

function mymodule_form_ajax_callback($form, $form_state) {
  $form ['simul_message_retour'] += mymodule_form_submit ( $form, $form_state );
  return $form ['simul_message_retour'];
}

function mymodule_form_submit($form, $form_state) {
    // Submitting part
}

Has anyone met this issue before with Ajax forms ?

Thank you,

EDIT: I just found that  the hook_form_submit is called BEFORE the hook_form_validate

Here you have the framework for Form-handling:

function customregister_custom_form($form, &$form_state){
  $form['first_name'] = array(
    '#title' => t('Vorname'),
    '#type' => 'textfield',
    '#default_value' => '0',
    '#required' => TRUE
  );
  $form['last_name'] = array(
    '#title' => t('Name'),
    '#type' => 'textfield',
    '#default_value' => '',
    '#required' => TRUE
  );
  $form ['submit'] = array (
    '#type' => 'submit',
    '#ajax' => array (
    'callback' => 'customregister_custom_form_callback',
      'wrapper' => 'customregister-custom-form'
    ),
    '#value' => t ( 'Lancer la simulation' ),
    '#weight' => 10000
  );
  return $form;
}

function customregister_custom_form_validate($form, &$form_state) {

  if (! is_numeric ( $form_state['values']['first_name'] )) {
    form_set_error ( 'first_name', 'ERROR !' );
  }
  if (! is_numeric ( $form_state['values']['last_name'] )) {
    form_set_error ( 'last_name', 'ERROR !' );
  }
}

function customregister_custom_form_callback($form, &$form_state) {
  drupal_set_message('custom_form_callback');
  //customregister_custom_form_submit($form, $form_state);
  $formular = drupal_get_form('customregister_custom_form');
  $formular = render($formular);
  return $formular;
}

function customregister_custom_form_submit($form, &$form_state) {
  drupal_set_message('custom_form_submit');
}


Filtering Views using referencing nodes I have a bit more complicated problem here, so I'll describe the background first.

In my Drupal 7 site, there are two content types: the 'car' and the 'inspection'. The only two important things about them is that the 'inspection' includes 'Date' field and that 'car' and 'inspection' are linked using Node References module (there's Node Reference Field named 'Car' in 'Inspection').

Now, here's my problem. I need to create a view that shows only the cars that haven't been on inspection in last two years which means that they have no 'inspection' with date > two years ago referencing them.

I'm able to achieve that if there's only one or none inspection referencing the car. In that case, I simply use 'Filter Criteria' on Date property of Nodes referencing this car (using relationships) and it works just fine.

However, if there are more 'inspections', the filter takes every single one and list the car whenever there's at least one with date < 2 years ago (even if there's another one newer).

What I need is to somehow create a filter that would consider all 'inspection' nodes that are referencing the 'car' and shows the car only if there was none that would be newer than 2 years ago.

I hope it is clear.

//I have one more smaller problem that is (probably) connected with this one. I need to show the date of the newest inspection of a car in a  view of cars. The view, however, always shows the oldest one (Table->Fields-> Date field of 'inspection'-> Nodes referencing this one 'car').

//BTW: If you don't understand the problem I have because of my level of English, please tell me. I'll try to rewrite it in a simpler way.

The first thing I would say is that it sounds as if you have node references going both ways. This is generally a bad thing in terms of database structures. In this case you should only have inspections pointing at cars and use reverse references if you need to do the opposite.

Anyway here's what I would do:

A view based on inspections, filter the content type to inspections only and also filter the date. That gives you all the old inspections.

Put the Car Node Ref into the field list and then Group By that field (Group By is under View > Advanced > Use aggregation)

You could then add a relationship based on the Car Node Ref which then gives you access to the individual Car fields.

This will give you one row per car for inspections older than [whatever you choose].

My only concern then is whether you might get a car which has inspections for >2 years ago and also more recent ones. So will appear in the list even though it has more recent ones.


Cannot alter title on user profile page I've created a custom module called renameprofile to alter the title on my user page, but it doesn't seem to be working. Any idea what is causing this issue? Btw this is on the ?q=user page.

renameprofile.module

<?php
function renameprofile_page_alter() {

  global $user;

  if(drupal_get_title() === isset($user->name)) {
    drupal_set_title('My Sharecab');
  }
}
?>

renameprofile.info

name = Rename user profile page title
description = This module renames the profile page title
core = 7.x

Yeah, that's an odd approach with === isset() basically checking if drupal_get_title == TRUE; whereas drupal_get_title returns a string title.

Something like this should work, in template.php or module (clear cache).

It will set the $title variable for page.tpl.php

/**
 * Implements hook_preprocess_page
 */
function MODULE_preprocess_page(&$variables){
  // Set title on user account pages.
  if ($account = menu_get_object('user')) {
    $variables['title'] = t('My Sharecab');
  }
}


how to read csv file in drupal 6 I want to read a simple csv file having 6 rows and 2 columns :

   **name   |  value**
    AJW097  |   1
    BDV763  |   1
    PVWC67  |   1
    WPC028  |   1
    TGI0227 |   1
    W5615C  |   1

I had saved this file here sites/default/files/csvfile.csv

here is the code i am using:

function my_module_form($form, &$form_state) {
$form = array();
  $form['browser'] = array(
    '#type' => 'fieldset',
    '#title' => t('Browser Upload'),
    '#collapsible' => TRUE,
    '#description' => t("Upload a CSV file."),
  );
  $file_size = t('Maximum file size: !size MB.', array('!size' => file_upload_max_size()));
  $form['browser']['upload_file'] = array(
    '#type' => 'file',
    '#title' => t('CSV File'),
    '#size' => 40,
    '#description' => t('Select the CSV file to be upload. ') . $file_size,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Upload CSV File'),
  );

  $form['#attributes']['enctype'] = "multipart/form-data";
  return $form;
}

function my_module_form_submit($form, &$form_state) {
  $filepath = $form_state['values']['upload_file']->filepath;
  $fp = fopen($filepath,'r') or die("can't open file");

print "
\n";

while($csv_line = fgetcsv($fp,1024)) {
    print '
';
    for ($i = 0, $j = count($csv_line); $i < $j; $i++) {
        print ''.$csv_line[$i].'	';
    }
    print "
\n";
}
print '
';
fclose($fp) or die("can't close file");
}

The problem is it is not reading the file and every time i click on Upload CSV File button it dies and say: can't open file.
where i am doing wrong?

try function form submit like:

function my_module_form_submit($form, &$form_state) {
  $line_max = variable_get('user_import_line_max', 1000);
  ini_set('auto_detect_line_endings', true);
  $filepath = $form_state['values']['file_upload']->filepath;
  $handle = @fopen($filepath, "r");
  // start count of imports for this upload
  $send_counter = 0;
  while ($row = fgetcsv($handle, $line_max, ',')) {
    // $row is an array of elements in each row
    // e.g. if the first column is the email address of the user, try something like
    $mail = $row[0];
  }
}


How do I configure Content Security Policy for base64 images? I'm using the Content Security Policy module and I placed restrictions on img-src.
Set to Self.
Additional sources:
https://www.google-analytics.com https://ssl.gstatic.com https://www.gstatic.com https://www.googletagmanager.com

However, my logs are filled with messages like this:

[Report Only] Refused to load the image
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAD1JREFUeNpiYGBgOADE%2F3Hgw0DM4IRHgSsDFOzFInmMAQnY49ONzZRjDFiADT7dMLALiE8y4AGW6LoBAgwAuIkf%2F%2FB7O9sAAAAASUVORK5CYII%3D'
because it violates the following Content Security Policy directive:
"img-src 'self' https://www.google-analytics.com
https://ssl.gstatic.com https://www.gstatic.com
https://www.googletagmanager.com".

How do I allow the base64 images provided by Drupal (jsonapi in this case)?

Based on this Stack Overflow answer, you need to add data: to Additional Sources:
data: https://www.google-analytics.com https://ssl.gstatic.com https://www.gstatic.com https://www.googletagmanager.com


user_login_block doesn't display message I have created an installation profile.
On one page i have added block using user_login_block form.

Now on the page there are other blocks also present.

Now when i submit the form without username and password, it should show me the form error, but it shows this message on next page reload.

I have checked $message variable is printed on the page also.

When i write any wrong password and try to login it will not show wrong username password message at that time, but when i reload the page second time at that time message will appear.

Has anyone faced such kind of situation. ?

Thanks in advance..

I successfully managed and fix it.
The code i was using to display the login block was as below
print drupal_render(drupal_get_form('user_login_block'));

This block used to generate the login block for the login functionality.
Now i tried to render the messages using theme_status_messages() function.
To fix the issue i created a function in my template.php file named THEMENAME_get_login_block().
In this function i added the theme_status_messages() function for the displaying the messages. So my function looked like given below.
function THEMENAME_get_login_block() {
    $form = drupal_render(drupal_get_form('user_login_block'));
    $messages = theme_status_messages();
    return $form.$messages;
}

And to render the block i used print THEMENAME_get_login_block();
This solved my problem. But still i am curious to know the root cause of such kind of events.
Any suggestions are welcomed....


Theme a Page Node Not All Page Nodes I have a page of node type: Page with the name 'latest'. I was looking at a module that lets me arse about with the comments form and things and i was wanting to add some code just to that one page. Not change all the Page content type.

Im sure i added something to my template, a preprocess thingy to achieve this before. Im using Drupal 6. Could anyone point me in the right direction? thanks.

I'll go see if theming a node is the same but ive a feeling from past experience i have to add something. Knowing me ive probably still got the preprocess thingy in there. ill go check.

I believe you are looking for template suggestions, see Drupal 6 Template Suggestions, one of the Drupal provided theme suggestions will do it for you.

I think the one you are looking for is page-node-[node-id].tpl.php

Alternatively you can create your own theme suggestions, see Working with template suggestions

Edit: It depends on what you want the code to accomplish if this answer is correct or not, if it's something related to display then templates may be correct, but if it's data manipulation then you may be better off with template_preprocess_node

Alternatively if you want to execute arbitrary code not directly related to just the theming of the node, I think you would use hook_nodeapi or hook_view


Show parent taxonomy term in view I have taxonomy countries list with cities

Czech Republic
 - Prague
 - Brno
Germany
 - Berlin

Then I have content type position where I am using this taxonomy as select list. Now I need to create table with list of this content type.

Wanted result:

Country       || City
--------------||------
Germany       || Brno
Czech Republic|| Prague

I have created view for that, but I am not sure how to show parent of taxonomy term.

I have found that How to show the parent and child taxonomy term? but I do not see Taxonomy term: Term ID, Taxonomy term: Parent term at all

First you need to create a Taxonomy term on node relationship to your vocabulary and name the identifier term
Then create a Taxonomy term: Parent term relationship using the previous identifier (term) as relationship and name the identifier  parent
Create a Taxonomy term: Parent term contextual filter using term as identifier
Lastly, add a Taxonomy term: Name and use the parent relationship


how to value from one view to another view filter in drupal I want to pass the value from one view to another view's filter I have view 'filter' which is having the select box with taxonomy list as option 'category_taxonomy' having fruits,vegetables. I want to pass the taxonomy value to next view in on change event to filter the value in view 2.My both 'view1' and 'view2' are in same tpl.If I select the value from view1 I wat to send the argument to the second view and and filter the result and then reload only the second view(view2).

$vocabulary = taxonomy_vocabulary_machine_name_load('service_line');
$terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocabulary->vid));
// print_r($terms);
echo '<select class="filter"><option value="">select</option>';
foreach($terms as $data){
  echo '<option value='.$data -> name.'>'. $data -> name.'</option>';
 }
echo '</select>';

One way to do it is to create a jumpmenu in your view's template and add it to the page that way instead of trying to do it with filters.

So in your view's Advanced tab, click on "theming" option, and a dialog box will open with your view's template name. Copy the views.tpl from the views module to your theme and name it that template name. Inside this template you can now find the place you want to output this jumpmenu and add the tax_terms code you have above. Only instead of outputting the options as a form field, convert them to links using JS here's one example. Or you can also create the jumpmenu as ctools like here.


Link path auto url to view field Does anyone know if its possible to attach a link to a specific node in a custom view and have that link be the path auto link?

I have a custom view that pulls in a title text field from an article. I want to have that text field be a link to go to that article and I only seem to be able to create a link to the node via a token the references the 'Content: nid' which outputs my link as www.site.com/node/66. I instead need the path to be my pathauto link.

Is this possible?

Add a field Content: Path This would add another token which would be the aliased path of the node you can use that.

Please note that to use a token with in view the field should be above the field being used.

By the if you just want to Link the Title to its node then you can simply tick "Link this field to the original piece of content" This would link it to the article that the Title points to with the aliased url


Create a field programatically with let me to introduce two values I don't want to use field_collection ;) I'll be easy.

I want to build a module that create a a field that let me to save two values at the same time, name and date.

I'd like to have both in the same table, but I don't find any article that explain how to make/define it.

It will be a field with two fields to fill in a node.

Any idea?

Thanks.

Download the examples module and look through the Field Example module.

It contains extensive code examples that show you in detail how to create a custom field, widget and formatter.


Hide submenu of Revisioning-module I would like to hide the items marked in the image. But as it turns out, they aren't stored an Array as we are used to in Drupal (at least as far as I can see).
How can I unset or hide them. Hiding by using CSS isn't an option.

I am not sure if you use drupal 6 or 7

You can configure this:

go to:  http:/your.drupal/admin/user/permissions
CTR + F do search on page and search for this both permissions:
unpublish current revision
delete archived revisions

But if also admins should not see this any more, you have to modify code:
(here for Drupal 6)

edit sites/all/modules/revisioning/revisioning_theme.inc
search for: unpublish current revision
4 rows below you will see:  $links[] = $link;
change it to: // $links[] = $link;
now search for: delete archived revisions and do the same
save and done


enforce naming conventions for page aliases by content type I would like to set mandatory url naming conventions for custom content type nodes.

When users create a new content type I want to force certain naming conventions for the url alias. For example:

when creating 'Type A' and 'Type B' pages they should have aliases of the form:

www.example.com/a/{user-assigned} (Type A)
www.example.com/b/{user-assigned} (Type B)

is there a way to do this in Drupal 8?

Yes, this use case is covered under the Pathauto module.

Essentially, you'll add a new Content patterns (from the admin UI in admin/config/search/path/patterns) for each of your content types with the following path pattern, my_type/[node:author:account-name].

As long as the user doesn't have the Administer URL aliases & Create and edit URL aliases permissions, their created content path will be set automatically without being able to change the path.


How to enable block programmatically I need to enable block from my custom module, to show block when the module is enabled, I set the status 1, but nothing happens until I manually change in Structure > Blocks .

function test_block_info() {
   $blocks['my-block-id'] = array(
    'info'   => t('My block'),
    'status' => 1,
    'region' => 'sidebar_first',
    'cache'  => DRUPAL_NO_CACHE,
      );
    return $blocks;
 }

For drupal 7 the best way will be write hook_enable function in *.install file of your custom module:

<?php

function YOUR_MODULE_NAME_enable() {
          $blocks = array(
            array(
              'status' => 1,
              'weight' => 20,
              'region' => 'sidebar_second',
              'visibility' => 1,
              'pages' => "instruments/*",
              'module' => 'instruments',
              'delta' => 'instruments_sidebar',
              'theme' => 'markets',
            ),
            array(
              'status' => 1,
              'weight' => 19,
              'region' => 'sidebar_second',
              'visibility' => 1,
              'pages' => "instruments/*\n<front>",
              'module' => 'instruments',
              'delta' => 'instruments_search',
              'theme' => 'markets',
            )
          );

          foreach($blocks as $block){
            db_merge('block')
              ->key(array(
                'module'=>$block['module'],
                'delta'=> $block['delta'],
                'theme'=> $block['theme']
              ))
              ->fields(array(
                'status' => $block['status'],
                'weight' => $block['weight'],
                'region' => $block['region'],
                'visibility' => $block['visibility'],
                'pages' => $block['pages'],
              ))
              ->execute();
          }
    }

This is code from my custom module, and it works :)
Here I enable my custom blocks, so I modify 'block' table. For custom blocks you should update 'block_custom' table too.

If you don't know how drupal store settings, just make changes manually and then check DB.

NOTE: db_merge function is very useful - it inserts data if they absent (if you just installed your module) or updates it (if you disabled and then enabled module)


Update cart on checkout page with tax rule I have a tax rule which applies when a user uses Utah as shipping place.But it takes a review order page in between to make it work. Is it possible to update the cart on checkout page soon a user chooses Utah as state.

There is no way right now to show the update without custom code, though it could be done by adding AJAX functionality to the form like the shipping module does. You can see how it updates shipping rates when address data is entered, and if I'm not mistaken it even provides a hook for you to add additional AJAX commands to the response. You should be able to update the order at that time and update the cart contents checkout pane display, too.


Ultimate Cron Background Process Taking a Long Time I'm having background process on Ultimate Cron process various queue items, but the fastest it usually processes them is at least one minute, and sometimes 3 minutes per item.

This seems incredibly slow to me.

Should I increase the number of threads? I'm not finding much documentation on how to speed up the process - I don't mind if it requires a bit more processing power - this is a required operation for the Drupal install in question, and it has to be run pretty much all the way through every 15 minutes.

There are no errors, just very slow processing.

I think we need to check from start to end point. This issue is like some processes which takes more time to execute. So we need to check what is that process and we can find that using Elysia Cron plugin.

This plugin helps you to find which cron process has taken much time and where to take possible actions.

PS: If this stuff helps you please leave me a comment and support :)

Thanks!


Site down after upgrading Views I have the CK profile installed and found a strange behavior in Views installed along with it (no Term ID filter criterion available), so I decided to upgrade Views to the latest dev build. I deleted the Views folder from the profiles/commerce_kickstart/modules and now my admin won't work. The error messages vary over time, but they relate to include files missing, such as:

Fatal error: require_once() [function.require]: Failed opening required
 '//profiles/commerce_kickstart/modules/views/plugins/export_ui/views_ui.inc'
 (include_path='.:/:/usr/local/php/pear5') in /profiles/commerce_kickstart/modules
 /ctools/includes/plugins.inc on line 468

How do I resolve the situation? And, most importantly, how should I proceed next time to perform a safe update of individual modules from the profile.

I don't think there is really a "100% Safe" solution for upgrading your modules. But for the future, the best thing that you can probably do is:

Make sure that you are using a version control system such as CVS, SVN, Git, etc. That way when you update and see that things go south you can always revert your changes.
Always backup the database before running update.php. Again, if things don't work out, you always have a restore point.
It is a good practice to read the release notes of the version that you are upgrading to and to take a peek at the issue queue of the module in question. Most likely another Drupal developer would have tried already to perform the same update that you are trying to perform, and there is an entry in the issue queue indicating what was the problem when updating. Sometimes if there's an entry in the issue queue it will also tell you how to upgrade from one version to another. Sometimes you can upgrade without no problems, sometimes you can't, and other times you have to follow a few manual steps before upgrading.

As for the present tense, since you already attempted the upgrade, I would start by following step #3 above, and if you can't locate a relevant entry in the Views issue queue that points you in the right direction, you're more than welcome to open one.


how can i access a node variable inside of theme_preprocess_page function? I'm trying to access a node variable, the id of a taxonomy term but i have to do it at the page level in theme_prepocess_page function. i did it in preprocess node like this

$libStatus = $vars['field_feature_library_status']['und'][0]['tid'];

in preprocess_page i tried this:

$libStatus = $vars['node']['field_feature_library_status']['und'][0]['tid'];

but i get this error...  Cannot use object of type stdClass as array in….

can someone explain how i can access this node variable in theme_preprocess_page function?

Have you tried field_view_values() and field_get_items()

function mytheme_preprocess_page(&$variables) {
    if (!empty($variables['node'])) {
      $output = '';
      $node = $variables['node'];
      $items = field_get_items('node', $node, 'field name');
      foreach ($items as $item) {
        $field_output = field_view_value('node', $node, 'field name', $item);
        $output .= render($field_output);
      }
      // Set $variables with the value you need.
    }
  }

Explained in here how to access node variables in region preprocess function?

I think you should also be able to use entity_metadata_wrapper as follow

$node = $variables['node'];
$wrapper = entity_metadata_wrapper('node',$node);
$libStatus = $wrapper->field_feature_library_status->value();


Using images in custom module (not through css) I am making a flex slider module, and it needs to just load some images statically, the only way I was able to get hold of any of the images was when I used a relative path in a background-image: url(relative-path-to-image) in a css file, but I am not interested in loading it through css.

If I try to access it relative from the template, using <img src="relative-path-to-image"> it won't work of course, because the src tag are being loaded on the client. I have looked a bit at the templating system and I can use a {{ directory }}  variable inside of twig, to maybe get the absolute path to the images right. But I just feel like even if I made that work it would still be a disaster implementation.

So my question is, if you need to add a  tag and give it a src path-to-image, what is your go-to solution to get that image accessible?

If you want to access images in the module folder:

preprocess function (assuming page, but can be any other template):

mymodule.module:
function mymodule_preprocess_page(&$variables) {
  global $base_root, $base_path;
  $variables['image1'] = $base_root . $base_path . drupal_get_path('module', 'mymodule') . '/images/' . $image1;
}

twig:

I don't know your logic for multiple images, I guess you have to code a loop for this.

But accessing static images in a module folder is not a cms way to do this, I would put the images into a node. You can make a content type "slider" for this and then access the absolute path of the image field:

twig:

Here you can code a twig loop to access multiple images in the field.


LoginToboggan redirect to the same page on Drupal-7 I have a Drupal-7 website and I use LoginToboggan module for login.
Is there a way to override this module or change the settings, in order to redirect users to the same page after successful login, and not on the user's profile page?

I found the answer, what did it was the Login Destination module!


How to make a collapsible fieldset in my theme? I want to have collapsible fieldsets in my Drupal 7 website in add content. I added this in html.tpl.php of my theme:

<?php
print $styles;
drupal_add_js('misc/form.js');
    drupal_add_js('misc/collapse.js');

?>

But nothing happend to my fieldsets.
Here's a sample code of fieldset I have used:

<fieldset id="fieldset-id" class="collapsible">
  <legend>Fieldset title</legend>

Fieldset description

     Fieldset content

</fieldset>

What is the problem?

Your theme might include jQuery 1.9. With this, I observed in Drupal 7.34 that fieldsets would not work (always shown collapsed, unclickable). Also CKEditor would not load (using the ckeditor module) and there might be other JavaScript related misbehavior.

To solve this, use jQuery 1.8 instead. I recommend the module jquery_update to handle jQuery versions in Drupal.


How to get field mapping information in custom module? I am trying to call field_info_field_map() in my DefaultForm.php . What is the right way? I am getting the following error:

  Error: Class 'Drupal\module_name\Form\Field' not found in
  Drupal\module_name\Form\DefaultForm->module_name_settings_get_field_options()

The code I am using is as follow:

$fields = Field::fieldInfo()->getFieldMap();

the code i am trying to convert to d8

function mn_settings_get_field_options() {
  static $options = null;
  if (is_array($options)) {
    return $options;
  }
  $options = array();
  $fields = field_info_field_map();
  foreach ($fields as $field_name => $field_data) {
    if (isset($field_data['bundles']['node'])) {
      $node_types = $field_data['bundles']['node'];
      $options[$field_name] = $field_name . ' (In content types: ' . implode(', ', $node_types) . ')';
    }
  }
  asort($options);
  return $options;
}

Looks one potential solution is to use is EntityFieldManager::getFieldMap. See the change log for this change.

Also, FYI:

  When working directly with an $entity, the field definitions (which include base and configurable fields) can be directly requested from the object with $entity->getFieldDefinitions() or $entity->getFieldDefinition($field_name)


How to migrate fields attached to files? I'm writing a file migration using migrate/migrate_d2d to migrate files from one Drupal 7 installation to another.

Images have custom fields attached to them, including a text field "field_boilerplate". This field exists in the destination site's image type. When I run the migration, the image itself migrates and creates an image entity, but field_boilerplate is not populated.

What am I doing wrong, and how can I migrate fields attached to files?

In mymodule.module:

/**
 * Implements hook_flush_caches().
 */
function mymodule_flush_caches() {
  mymodule_migrate_register_classes();
}
/**
 * Register dynamic migration classes
 */
function mymodule_migrate_register_classes() {
  // Arguments common to all migrations
  $common_args = array(
    'source_connection' => 'mysite_legacy',
    'source_version' => 7,
    'group_name' => 'mymodule_migration',
  );
  // Other migration arguments redacted for length
  // Image migration arguments
  $image_args = array(
    'machine_name' => 'images',
    'class_name' => 'MyModuleImageMigration',
    'description' => t('Migrate images'),
    'user_migration' => 'users',
    'default_uid' => 1,
    'source_dir' => 'http://example.com/sites/default/files',
    'destination_dir' => 'public://',
    'skip_pictures' => TRUE,
  );
  Migration::registerMigration('MyModuleImageMigration', 'images', $image_args + $common_args);
}
/**
 * Implements hook_migrate_api().
 */
function mymodule_migrate_api() {
  return array('api' => 2);
}

In an included file:

<?php
class MyModuleImageMigration extends DrupalFile7Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);
    // Mappings
    $this->addFieldMapping('field_boilerplate', 'field_boilerplate');
  }
}

You need to specify the bundle type when registering the dynamic migration:

  $image_args = array(
    'machine_name' => 'images',
    'class_name' => 'MyModuleImageMigration',
    'description' => t('Migrate images'),
    'user_migration' => 'users',
    'default_uid' => 1,
    'source_dir' => 'http://example.com/sites/default/files',
    'destination_dir' => 'public://',
    'skip_pictures' => TRUE,
    'bundle' => 'image', // Need to add the bundle type
  );
  Migration::registerMigration('MyModuleImageMigration', 'images', $image_args + $common_args);


Content publishing and confirming comment via email in drupal 7? I want to provide following functionality:

When a user sends a mail to publisher@mysite.com, the subject of email become title of a blog post and body of email become body of blog post and the post should be published if the mail is done by admin
If the mail is not done by admin then a mail should go to admin notifying same and if admin replies "publish" then it should be published else it should not be published

Currently there is no module for this functionality afaik.

To implement this one,

You need to pull the mails from server
Processing the mails and performing other operations like checking whether the user is an admin
After the processing create the content
Finally add a cron job to perform this operation regularly

This article provides info about how to achieve this feature in drupal 7 with combination of several modules.

However authenticating using the sender's mail will be a security risk. For example if the admin mail ID is exposed then anyone can send mails as admin by altering the header information.


Translated Taxonomy terms in node creation page? Drupal 7 multilingual website(English and Arabic):

I have a taxonomy term named "Food Category".Added some terms in it.Also i added translation for each terms .

I added a field to select the term in a content type :

LABEL : Select List Food Category Item

MACHINE NAME : field_list_items

FIELD TYPE : Term reference

WIDGET : Select list

I want to show the Arabic terms when i translate a node to Arabic.Now it is in English only.

Please advice me.

I found the solution :

admin/config/regional/i18n/select

CONTENT TO FILTER BY LANGUAGE
 Select nodes by language
 Select taxonomy terms by language

unselect

  Select taxonomy terms by language


Can I have multiple nested forms within the same fieldset? I am building a custom module that adds a form to certain node types that allows the user to fill/save some additional information about the node.

I would like to have 2 buttons. 1 which saves the data entered (currently working) and another which posts the data to an external script.

I can get this working by creating two different forms and settings their #action's accordingly but I would like the form markup all in a single fieldset, is this possible?

You can have both buttons in the same form. Inside the form's #submit handler (or each button's separate #submit handler), based on which button has been used to submit the form, you can either save the data, or do a drupal_http_request() to execute the external script.

Your form would include buttons roughly like this:

'save' => array(
  '#type' => 'submit',
  '#value' => t('Save'),
  '#submit' => array('save_function_name'),
),
'process' => array(
  '#type' => 'submit,
  '#value' => t('Process'),
  '#submit' => array('process_function_name'),
)

Then, the two functions save_function_name() and process_function_name() would do the job.


Do I have to unistall the disabled modules? I'd like to know if there is any difference between disable or uninstall modules regarding performance.

Will having 10 disabled modules affect my site performance? Will the performance be better if I uninstall them?

Disabled modules do not get executed so they should not affect performance but they may have variables and database tables that still exist. If you are not planning on using those modules again it is highly recommended to use the uninstall process at admin/build/modules/uninstall in D6 or admin/modules/uninstall in D7.


Display a block based on the term reference field of the current node What I'm trying trying to do sounds fairly simple, but I can't get my head around it.

I'm having 2 taxonomy vocabularies: machinery and batteries (both created with NAT for all that matters), and 2 content types which are named the same.

Both the content types provide the ability to check related items (a regular term reference field). For the machinery node the user can check which batteries are suitable, and for the battery node the user can check which machines use this battery.

Basicly what I'm trying to is: if you're on a page about a specific machine, it should show the batteries that are related to it, be it as teasers (or fields) in a block. And vice versa: when you're on a page about a specific battery, it would show all the machines in which it fits.

I've been boggling around with relationships and contextual filters, but it just wouldn't work out so far (spent a couple of hours here). Does anyone have an idea how to sort this out please?

There's possibly an easier way with the References module. In that case it wouldn't even require NAT, but just a View with contextual filter based on the Reference field.


Using hook_theme_registry_alter to only modify specific pages instead of all pages I have a custom module which invokes the hook_theme_registry_alter() to modify the presentation of some input fields.

However, I've discovered that the overridden styling is affecting ALL input fields on my entire site.

This is not good!

How to I make it so that my implementation of the hook_theme_registry_alter() is only seen on my module's pages?

Here is my function, and it is applying the theming functions to ALL radio and form elements on our site.

function MY_MODULE_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['radio'])) {
    $theme_registry['radios']['function'] = "MY_MODULE_radios";
    $theme_registry['radio']['function'] = "MY_MODULE_radio";
    $theme_registry['form_element']['function'] = "MY_MODULE_element";
  }
}

For simple alterations, instead of implementing hook_elements(), you could simply implement hook_form_alter() or it's cousin hook_form_FORM_ID_alter(). Both of these functions will effectively allow you to (as their name suggests) alter a form's input elements, and they are much easier to implement than hook_elements(). The former gets called for every function in the website, while the later only gets called for the FORM_ID that you specified in your hook implementation.

If the ID of the form you wish to modify is my_form, then hook_form_FORM_ID_alter() would be written as hook_form_my_form_alter(). If you want a more thorough explanation of these two hooks, I highly recommend reading Lullabot's writeup on modifying Drupal 6 Forms.


Error message when uploading an image During Image upload, I get an 'Http error 0 occurred' when the file size is larger than the allowed maximum file size. Is this a correct behavior? and how would I provide a better error message. I have tried this in different browsers all show this message and changed settings in php ini file based on discussions on this topic.

Thanks for your help.

You're going to see this error when you try to upload an image file that PHP has an issue with, either because it is larger than the allowed maximum file size in PHP or because trying to process the image (ex. for creating thumbnails) is consuming more memory than you have allowed in your php.ini.

There is a monster thread on this topic over at Drupal.org but the key takeaways are to try and increase these two values (php file upload or memory limit) or to switch your imageapi library from PHP GD over to ImageMagick to avoid the memory constraints.


Limited promoted nodes with order I was wondering what is the best way to promote nodes into a page (ie front page).

Drupal comes with its own "promote to front" option and we have other ways such as using Flags modules for this purpose as well, but I need two features that none of those cover.

One is that I only want for example 5 nodes be promoted at the same time, so if the client promote one more node, one of the previous nodes will automatically be removed from the list.

Also I'd like to be able to set the order (weight) of those promoted nodes too.

I have tried to use views and draggableviews for ordering the nodes which works great but can't figure out how to limit the number of promoted nodes?

Many thanks

In Views, you can set the number of values returned in the pager config by selecting 'Display a specified number of items'. Have you tried that set to 5?

If you said something like 'the top 5 in the draggable views list will be displayed' in the help/description that would do it for your users, plus they could then bring back stuff if they wanted without having to go out and reflag it. to automatically unflag content, you could hook into hook_flag() and unflag the oldest or something with some custom php code.

Check out The Flag PHP API, which talks all about that kinda stuff.


Move a Webform between sites I built a few webforms on a Drupal 8 install. I see how to export the webform in YAML via the export tab on the webform.

How do I import that YAML into another site to re-create that webform?

Thanks in advance.

The simplest way would be to go to /admin/config/development/configuration/single/import, select Webform and paste the YAML.

More information: Configuration Managment.


In Views, how do I get a link directly to an image file (not the node containing the image file)? I have a view that displays nodes in fields format.

I have a Global text field in which I want to display the URL of images contained in nodes; however, I can't find how to get the URL of the images.

What I've tried:

I added the Image field and chose "Content" as the option for "Link to."  This is the link I want, but this prints out the image too (I don't need the image) and I can't use this field as a replacement pattern.
I added a link to the content itself, but then this gives me a link to a node, not the image.

In Views, how do I get a link directly to an image file (not the node containing the image file)?

An option that doesn't require installing a new module:

Create a Relationship to the image for which you want to create a link
Add a field File:Path
Exclude from display
Rewrite Results - output this field as a link
Add the replacement pattern to your global text


How can I get the tid (term id) using the id of my node in .theme I need to get the id of the node category.

I try this:

$variables['tid'] = $node->field_category->target_id;

I wrote this answer thinking the question was for Drupal 7. This is not accurate for Drupal 8.

If you debug the $node object, you will see that it's more complicated than that. It has a language and probably a value index. So, you could access the TID this way:

$variables['tid'] = $node->field_category[LANGUAGE_NONE][0]['target_id'];

But, don't do it that way. It would be better to use EntityMetadataWrapper. The code should look something like this:

$wrapper = entity_metadata_wrapper('node', $node);
$variables['tid'] = $wrapper->field_category->raw();

If you want the whole term object, you can do this:

$variables['term'] = $wrapper->field_category->value();


How to show Comment Count in node template? How can I show Comment Count in a specific place of the node template?
I want to show Comment Count's of a node (article) in the submitted area instead of in the node links area. I do this already in Drupal 7 with this codes in node.tpl.php:

<?php if (module_exists('comment') && $node->comment) { print t('Comments'). ': ' .$node->comment_count;} ?>

or this code:

<a href="<?php print $node_url;?>#comments"><?php print t('Comments'). ': '. $comment_count; ?>

What is the equivalent code for Drupal 8?

Use this code in your theme's YOUR_THEME.theme file:

function YOUR_THEME_preprocess_node(&$variables) {
  // Note: you'll probably want this only for certain content types.
  if ($variables['node']->getType() == 'YOUR_CONTENT_TYPE') {
    $variables['comment_count'] = $variables['node']->get('YOUR_COMMENT_FIELD')->comment_count;
  }
}

And then you can use it in your node.html.twig file like so:

{{ comment_count }}


How To Deal With Datebase Size? I'm using domain access sharing the same database for 6 different sub domain websites

My concern my database limit is 1000MB

Is there a way to create new database set to a limit for example every 700MB

What the best way to deal with large database size?

Put your session and cache data in memcache or APC.
Use non-database log backend.

Don't store logs to long, if you have to keep them in DB.

If above fails, just change your hosting company or hosting plan, to get bigger limit. Database space is cheap nowadays.


How can I display the list price field in product page? I am new to commerce Kickstart. I can add the list price field in hats content types. But i can't to show the list price field in product page. I don't want to show the SKU field in product page.In node--product-type.tpl.php

.. But it doesn't work it..

it much be easier to add a 'product reference' to your product type when you define the 'content type'. and simply the 'Product: Price' field will add to your 'manage display' in that 'content type'
if the price doesn't show up, Modify the settings for the price field on the product type "manage display" configuration.


Local and global copies of module? I have a module I'm developing that will be used by several sites.

I have a "preview" site on the same server that I would like to be able showcase new features in before promoting to the production sites.

I thought I would be able to have the production version in the drupal/modules directory, and the preview version in the drupal/sites/preview_site/modules directory. I had expected Drupal would load the module from the site's directory and ignore the copy in the global modules directory.

However, when I do this, I get the following error:

  PHP Fatal Error: Cannot redeclare

It would seem that Drupal is trying to load both copies!

Is there some way I can get it to only load the local copy?

Is there a better way to achieve this (I expect lots of people will say don't put the preview site on the production server.)

I have discovered that this wasn't a problem after all.

I think the error I initially got (on performing a "clear cache") was caused by the original version of my module already being loaded from global version, and loading again from the local version caused the "redeclare" error.

If I had just reloaded the page, Drupal would now know to load from the local copy, and ignore the global one.


Hierarchical taxonomy breadcrumb I have a view that displays terms hierarchically via a view attachment, but neither the URL nor the breadcrumb keep track of where it is in the hierarchy. For example, a taxonomy structured like the following.

Category

Term I

Term A

Term 1

Term II

Term B

It displays a page listing Term I and Term II. Upon clicking on Term I, the user is taken to the page for Term A, which is a list of its sub-terms (Term 1). Upon clicking, the user is taken to a list of nodes tagged with that therm.

The path and breadcrumb for each of these pages is, sequentially, the following.

/category
/category/term-i
/category/term-a
/category/term-1

I would like instead for the breadcrumb and path to be the following.

/category
/category/term-i
/category/term-i/term-a
/category/term-i/term-a/term-1

I've tried the Hansel and Custom Breadcrumbs modules, but I have been unable to configure them properly, or they just don't provide the functionality I need.

I'm using Drupal 7 with a theme based on Omega, so any answer that include instructions to insert code into template or other theme files need to include information about where that code belongs in Omega.

These are two separate questions. One about the path, another about the breadcrumb.

Breadcrumbs:

Disclaimer: The solution presented here may need more tweaking, if your taxonomy/term/% is replaced by a views page with contextual filter. (I never do that, there are other ways to achieve the same)

Crumbs will do the trick. 90% of the task out of the box. If not, check this doc: http://drupal.org/node/1984484

You need some manual work to make "/category" the top-level breadcrumb item for all the terms: (this explanation is for the 7.x-2.x branch)
Visit Admin > Structure > Crumbs > Entity parent > Taxonomy
Set 'category' as the parent path for your vocabulary.
Go back to Admin > Structure > Crumbs
Move crumbs.entityParent.* into the "Enabled" section, and give it a low enough priority.

Path:

I suppose you have pathauto installed already.
Go to Admin > Configuration > Search and metadata > URL aliases
Look at "Taxonomy term paths".

I read somewhere that the following pattern will do the trick:

category/[term:parents:join-path]/[term:name]

Not tested myself. Good luck with it :)


Fatal Error: PDOException: SQLSTATE[42000] [1049] Unknown database I have a development site (site1) and created a second (site2) using drush, copied over all modules/themes and continued development. Both were working and I continued module updates in both.  When I returned to site1, I found an error message as follows:

  PDOException: SQLSTATE[42000] [1049] Unknown database 'mydevelopmentDB' in lock_may_be_available() (line 167 of mywebsite/includes/lock.inc).

There features and nodes I would like to use in site2 but I cannot access it. So I created a new site (site3) using drush, copied the contributed modules & themes from site2, and imported the database from site1 into site3, only to get the same error message as from site1.

As I interpret this, situation, the core and contributed module files in site3 should be good, the core is a fresh copy and contributed modules are taken from site2, which is working fine. The settings.php files are identical except for the database, username and password settings match the individual database name. The only difference is the database itself.  Can anyone help identify the table(s) that might have a setting that might cause this problem?

This isn't a problem with tables, it's a problem with the name of the database.

Drupal is successfully connecting to your database server, but it isn't finding a database with the name mydevelopmentDB (which must be the name of the database specified in settings.php).

To isolate the problem:

Open up PHPMyAdmin for the server in question and run this query:

SELECT * FROM mydevelopmentDB.users

If you get a similar error then you know that you've definitely got the wrong database name.
Make sure that the name of the database on the server matches the case of the database name in settings.php. Depending on your MySQL settings the server may or may not be enforcing case sensitivity on database/table names.


How can I create an alias to point to an uploaded file? Users uploading a file within content create a name like
my_site.com/sites/default/files/import/CrazyLongNamefile.pdf
They would like to alias it for referencing in other media (print) like
my_site.com/GoodName.pdf
URL alias works fine for other things, but not files (that I can determine)
The File (Field) module looks like it would probably do what I want, but it hasn't been touched for Drupal 8 in a while.
Is there a way (module, custom code) to provide an alternative path to a file that I can make available to content creators?

I agree with Clive and base oh his comment, to redirect all files to another route you can use .htaccess route direction. So,
first solution:
add to following line in your .htaccess file.
RewriteRule ^sites/default/files/(.*)$ /files/$1 [L,NC]

note: you can use whatever you want instead of files, like assets etc.
PS: if your files are Media types, with pathauto module you can create a pattern to redirect them additionally you can let the user override them the what path he wants.
second solution:
install https://www.drupal.org/project/file_entity module and then with pathauto module you can create an alias for files.  like files/file-title.
third-solution: use https://www.drupal.org/project/path_file module

The Path File module allows content editors to upload files and
specify the url at which they will be available. Normally, when
uploading a file to Drupal with the same name as an existing file, it
is given a new name instead of overwriting the existing file. This can
problematic when file urls are referenced in content, menus, etc but
may need to be updated in the future. The Path File module allows you
to mitigate the impact of those changes by setting up a canonical url
alias which will always point to the most up-to-date file


views custom link like page more link I want to add a custom link at the end of the loop of my view just like Pager More Link do. But I want to create a custom link. What I've tried so far:

I have created a Custom Text field, rewrote it to a link that I want and made it exclude from display. Then I group my this field and with css I place it where I want it. The only problem is that this grouped field is displayed with an <h3> tag that I don't want.

Is there any way to group field but not in tag <h3><h4>... or there is a module or something which can give me a option to create a link similar to the pager more link but with a custom url?

Why not add a Text area view footer field?

You can set it to full HTML and just add an HTML anchor there. Optionally there is checkbox to 'Display even if the view has no results'.

This adds a custom link below your view.


List all fields with the feature they are defined in I'm interested in generating a list of all fields with a column highlighting the feature that contains the field base setting and another column highlighting the field instance feature, (if the field is defined in a feature).

Something like this...

Field Name     |   Field Base Defined In  | Field Instance Defined In
field_subtitle |   mysite_shared_fields   | blog_story_feature
field_other    |   mysite_shared_fields   | blog_story_feature

Has anyone attempted this? Or can anyone suggest a solution.

Some useful functions /snippets below

field_info_instances();

$features_map = features_get_component_map();

$features_map['field_base'];
$features_map['field_instance'];
return;
foreach (field_info_fields() as $key => $field) {
  $base = isset($features_map['field_base'][$key]) ? join(',',$features_map['field_base'][$key]) : 'NOT IN A FEATURE!';
  $instance = 'todo';
  $rows[] = array($key, $base, $instance);
}
print theme('table', array('header' => array('machine_name', 'base', 'instance'), 'rows' => $rows));
return;

$components = features_get_components();
$field_base_component = $components['field_base'];
features_include_defaults($field_base_component);
$field_instance_components = $components['field_instance'];


Can't get form_state['values'] from a form on a custom checkout pane I created a custom checkout pane with Drupal Commerce so if a user checkouts as anonymous they can create an account on the checkout completion page.  The problem is that when in my form's submit function the form_state values are not passed and I get an undefined index error.
Here is the code for the checkout form:

function commerce_checkout_complete_registration_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {

      $form['new_email'] = array(
        '#type' => 'textfield',
        '#title' => t('Email'),
        '#element_validate' => array('_validate_the_email'),
      );

      $form['pass'] = array(
        '#type' => 'password_confirm',
      );

      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Register'),
        '#submit' => array('commerce_checkout_complete_registration_pane_checkout_form_submit'),
      );

      global $user;
      if($user->uid == 0){
        return $form;
      }

    }

And here is the submit function:

function commerce_checkout_complete_registration_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {
  dpm($form_state);
  $email_address = $form_state['values']['new_email'];
  syslog(1, $email_address . 'TEST');
}

The function "commerce_checkout_complete_registration_pane_checkout_form" needed to have the $form variable passed as a reference, &$form.


What is the best method to customize the display of author information on a node of a certain type? Requirements: For nodes of a certain type (blog), I need to show the author information with the author image using a specific Image Style, the user name, the user profile description, and another custom user field.

The method I'm currently using is implementing theme_preprocess_node() to create a variable to pass to my node--blog.tpl.php file that includes the elements I need themed. This means I have calls to theme_image_style() in my theme_preprocess_node() function.

Is this the best method, or is there a "more Drupal" approach I'm missing?

If it helps, here is a snippet of code:

/**
 * Hook theme_preprocess_node
 */
function hotness_preprocess_node(&$vars) {
  // for blog posts, style date and show intro image
  $node = $vars['node'];
  if($node->type == 'blog') {
    // nice date
    $vars['date'] = format_date($node->created, 'custom', 'F j, Y');

    // use image style for blog image
    $vars['blog_image'] = NULL;
    $blog_image = isset($node->field_blog_image['und'][0]) ? $node->field_blog_image['und'][0] : FALSE;
    if($blog_image) {
      $vars['blog_image'] = theme_image_style(array(
        'style_name' => 'introduction-image',
        'path' => $blog_image['uri'],
        'width' => $blog_image['width'],
        'height' => $blog_image['height'],
        'alt' => $blog_image['title'], // to make it easier to the end user I just show title
        'title' => $blog_image['title'],
         'attributes' => array('class' => 'blog-image')
      ));
    }

// I use user_load() because the node object doesn't have the user description.
$author = user_load($node->uid);

$author_image = '';
if(isset($author->picture->uri) && !empty($author->picture->uri)) {
  $author_image = theme_image_style(array(
    'style_name' => 'blog-author-image',
    'path' => $node->picture->uri,
    'width' => NULL,
    'height' => NULL,
    'alt' => t('User .') . $node->name,
    'title' => t('User ') . $node->name,
    'attributes' => array('class' => array('author-image')),
  ));
}

$author_name = l($node->name, 'user/' . $node->uid);
$author_desc = isset($author->field_description['und'][0]['safe_value']) ?
  '
' . $author->field_description['und'][0]['safe_value'] . '
': '';

// put it all together
$vars['author_block'] = $author_image . $author_name . $author_desc;

}
}

In your code at

 $node->field_blog_image['und'][0]

this is still an array so you need to access the value of the field one more level deep in to that array you can access it as follows.

$node->field_blog_image['und'][0]['safe_value']

Rest of code looks good to me.


Multiple products per display I'm working on a clothing store and I need to create a page type in which a model wears different pieces of clothes and users can see all the different products and add them separately to cart.

In other words, how could I have multiple products (of different kinds) on the same display, so that users can see the product of each product, choose sizes, etc., and add them to cart separately? (It's not a product bundle that you buy as a whole.) I've tried to create more than one product reference field, and I get multiple product-add-to-cart forms, but I can't have each product's price displayd separately. Is that possible? I can only display the price of the first product with the flag "Render fields from the referenced products when viewing this entity" checked.

You have at least 3 options:

If you're requiring all of the products to be bought together, you could use Commerce Bundle to create a Bundle Group product, and then add all of the individual bundle groups (e.g. a top, a bottom, and a pair of shoes) to it. This would then give you the ability to have all three products on a single page, but it'd require you to buy all 3 as a bundle.
You could create a node or a taxonomy page that simply references the node or products using entity or product reference fields. This would then give you multiple separate add to cart forms on a single page, (basically taking the three pages and combining them together).
Use Commerce Add to Cart Extras (or Commmerce's built-in views plugin) and build views which you could display on a node, panel, etc. Add to Cart Extras would allow you to build a form which would allow for bulk purchasing as well.


Drupal 8 Custom Composite Masked Input Are masked inputs supported in custom composites?

I've tried the following and it doesn't break but it also doesn't mask.

$elements['job_details']['job_phone'] = [
  '#type' => 'textfield',
  '#input_mask' => '(999) 999-9999',
  '#title' => t('Company Phone Number')
];

If you want to get simple form elements to include webform element enhancements you have to 'initialize' the composite's sub-elements using \Drupal\webform\Element\WebformCompositeBase::initializeCompositeElements


Redirect basic page to external url when visiting page I'm attempting to provide a field to users to enable them to enter an external url. If they enter a url I would like that basic page to redirect to the url the user provided instead of actually opening the node. I've made some attempts by using a preprocess node hook in my custom .theme file as seen here:

function mytheme_preprocess_node(&$variables){
    $node = Drupal::request()->attributes->get('node');
    $type = $node->getType();
    if($type == 'page'){
        $redirect = $node->get('field_redirect')->value;
        if($redirect != ''){

            $response = new Symfony\Component\HttpFoundation\RedirectResponse($redirect);
            $response->send();
            Drupal::entityManager()->getViewBuilder('node')->resetCache();
            return;
        }
    }
}

And I've also tried creating a module to do it and using an entity_view hook like so

<?php

function mymodule_entity_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
  if ($entity->getEntityType()->id() == 'node' && $entity->bundle() == 'page' && !$entity->field_redirect->isEmpty()) {
    $value = $entity->field_redirect->getValue();
    $redirect = $value[0]['value'];
    $response = new Symfony\Component\HttpFoundation\RedirectResponse($redirect);
    $response->send();
    return;
  }
}

Each of these solutions work the first time, but don't work the 2nd time or any time after that until I clear the cache. I'm assuming this is a caching issue. I've heard that using cache tags could resolve this issue but I'm not sure how I would use them. Also I'm not married to making any of these solutions work I merely want to implement some way to perform redirects on pages, it doesn't matter to me how.

Is it possible to perform redirects on node pages?

this is a cache problem. You need to set correctly the cache tags and context for the entity and it will work.
You need to do something like this to skip the cache:

  '#cache' => ['max-age' => 0],

you can find more info here: https://www.drupal.org/developing/api/8/cache/tags

Notes:

This needs to be put on hook_entity_view_alter() on the entity in your case the node, or if you want in just one field for which you want to set it. This is a work around for your redirect issue!
Try to add it to the $entity, if it doesn't work you need to replace the default '#cache' or you can add it to the $build array, this is case dependent.


Track clicks in Drupal 7 and querying with Views I'm looking to log clicks from generated URLs that are sent via email.  I need to be able to query these log entries and display the results to my users using the Views module.

What I need to track.

Unique ID from URL clicked.
Date and Time URL was clicked.
Node reference (Predefined from UID)
User reference (Predefined from UID)

Currently, my plan is to create a new content type and use references as a makeshift logging system, but this seems very bulky and expensive. Is there a way to drastically improve node_save() performance?

What would be the recommended way to accomplish a click log in Drupal?  Low overhead and Views integration are important.

You want analytics/statistics tracking on some urls ? This has little to do with emails, or Views.

Typically you would use something like Google Analytics. There is a free open-source version with Drupal integration called Piwik. The Piwik module lets users see analytics detail(s). You may be able to setup a "Goal" per user of the urls they should be able to see tracking for, see also the sister module Piwik Reports.

The builtin Statistics module can count page views ... you could try to integrate it into Views maybe if you want. The Statistics Pro module has no D7 port yet, and sounds like what you want.


How can I get data from ResultRow object in views template I am trying to theme a Drupal 8 views. When I print the row variable using kint method I am getting below result. But I'm not sure how could I access the values in the object.

I tried below options. But nothing works.

{{ row._entity.title.value }}
{{ row.contents.get('title') }}
{{ row.contents.contents.title }}

Could anyone please help me how could I iterate through row data in views twig template.

There are two question. First how to get the title in the kint dump?

{{ row._entity.title.value }} should work, also {{ row._entity.gettitle }} or {{ row._entity.label }}, because getTitle() and label() are methods of the node object.

Second, could anyone please help me how could I iterate through row data in views twig template?

In Views two steps are needed, first get the field and then use the method getValue() on the field providing the result row as parameter:

{{ view.field.field_name.value(view.result[0]) }}


How do I use a preprocess function for a node template? I'm trying to preprocess my variable array in drupal 8, But it's not working well.I'm checked with the Bartik theme also, But getting the same error here. When I'm trying to print the variable array its giving a blank page result. How can I preprocess my variable array for a node template?

`function bartik_preprocess_node(&$variables) {
  // Remove the "Add new comment" link on teasers or when the comment form is
  // displayed on the page.
  if ($variables['teaser'] || !empty($variables['content']['comments']['comment_form'])) {
    unset($variables['content']['links']['comment']['#links']['comment-add']);
  }
  print_r($variables);
}`

This is the function I'm tried to checkout the issue in bartik theme.

Instead of using print_r() enable devel module and their new submodule called kint. And use kint() instead of print_r(). You can also use print_r() but is messy.

  How can I preprocess my variable array for a node template?

function YOURTHEME_preprocess_node(&$variables){
  kint($variables);
}

If this does not work it might be a cache problem.  I will recommend you to set you website into dev mode using DrupalConsole. drupal site:mode dev

Why ?

  The Twig engine provides options for configuring debugging, automatic
  reloading (recompiling) of templates, and caching compiled templates
  in the filesystem. By default, the Twig theming engine compiles
  templates into PHP code and stores the compiled code in memory.
  Compiled code is unsuitable for development, since changes in Twig
  templates are not immediately updated in your Drupal site. Twig cache
  can be cleared through Drupal's clear cache interface, but for ongoing
  development it's easier to change Drupal's settings so that Twig
  doesn't cache anything at all.

Running  drupal site:mode dev will disable all twig cache. For more information about debugging please visit - Debugging compiled Twig templates


How do I create a configuration sync folder? I've inherited a Drupal 8 site but it has no config_HASH folder with it which means that the majority of admin paths throw an exception.

How do I generate a new configuration folder based on the current site?

To generate a new config folder do the following:

In settings.php add the following line:

$config_directories['sync'] = 'dest/to/config-sync';

This is relative to your docroot or index.php file.  My permission were set in a way that drupal could create this directory but you may have to create your own.  Next you will want to populate your sync directory with active config. Run

drush cex -y

Now your active config can be version controlled and deployed to your other environments. Remember to make a database backup first before importing config.


How close the admin overlay on submit for a drupal form shown within the admin overlay I'm currently showing a drupal form via the admin overlay. I'm using jQuery to perform the processing of the form.

The problem I have is how do I close the overlay on submit? right now the only way to close the overlay is by pressing the X at the top right (well based on the default theme), which is just a .

Now I'm presuming that I could somehow change the form to add the "overlay-close" to the submit button, but I'm not sure how to do this.

Is there a way to add a class to a button on a form in drupal?

Cheers,

James

I don't have experience with the admin overlay, but from what you are writing, I understand that you want to add the class "overlay-close" to an element (admin overlay?) when submit button is pressed. You can adapt the following code for that:

$('#form_id').submit(function(){
  // Add "overlay-close" class to the proper element
  $('#element').addClass('overlay-close');
});


Retrieve translated taxonomy term in current language programatically How do I retrieve a specified taxonomy term translated (if translation exists for this term) from the current language context programmatically with D8?

Use the following code:

$curr_langcode = \Drupal::languageManager()->getCurrentLanguage(\Drupal\Core\Language\LanguageInterface::TYPE_CONTENT)->getId();

// retrieve term
$taxonomy_term = \Drupal\taxonomy\Entity\Term::load($tid);

// retrieve the translated taxonomy term in specified language ($curr_langcode) with fallback to default language if translation not exists
$taxonomy_term_trans = \Drupal::service('entity.repository')->getTranslationFromContext($taxonomy_term, $curr_langcode);

// get the value of the field "myfield"
$myfield_translated = $taxonomy_term_trans->myfield->value;


How can I mass delete multilingual strings when I know only the page that added them? Some inappropriately placed t() functions generated a large number of strings that I do not want to translate.  Unfortunately, using the Refresh strings i18n page does not clear these strings.

On the Translate interface page, I can search for the strings one by one and delete them but there are about a hundred so I would prefer to do it another way.  Thankfully, they were all created on two pages, so I can search by the path (/ja/mypage) and delete them that way.  However, I still have to click each link.

Is there a faster way?

drush sql-query "delete from locales_source where location = '/ja/mypage'"

Or delete by strings, for examples if all strings you want to delete contains "hoof" :

drush sql-query "delete from locales_source where source like '%hoof%'"


Drupal7/Search Module & Pagination I am looking for a People directory Search Module.
Something like what they used on top of the link: http://wws.princeton.edu/directory
Also in the link above, they have pagination on the top and
bottom of the page.
In my case when I set the 'Pager' in Drupal Admin, it adds the pagination block to the
bottom of the page. How would I move it to the top instead?

Thanks.
Boutros.

Filter :

A views module will do the same with few tweaks on exposed filters

like:
 Name filter operator (starts with) and show all (a-z) characters with link each character accordingly.

Pagignation :

You can have pagination on top and bottom by overwriting that views template.
just print print $pager; where ever you required.

Its better to not load another modules help for something that can be achieved with small changes. :)


Create a field instance programmatically on a taxonomy vocabulary I'm trying to create a module which creates a taxonomy vocabulary on installation of the module, and creates one text field on the taxonomy vocabulary/term. But I'm getting the following error when I enable my module:

  [error] FieldException: Attempt to create an instance of field field_flickr_photoset on forbidden entity type taxonomy_term. in field_create_instance() (line 468 of
  /var/www/www.example.com/htdocs/modules/field/field.crud.inc).

First of al, why a Forbidden entity type? Is it not possible to create a field on a taxonomy vocabulary through code? Or am I missing some parameters?

I used very similar code to create a node type and attach fields to it, which currently works without any problems. I didn't think that changing the entity type would cause such problems.

I tried searching on google and here on how to do this, but all I get is people who are asking how to attach a taxonomy term reference field to a node type, which is not what I'm asking. It's attaching a text field to a taxonomy term/vocabulary.

If you look in taxonomy_entity_info() you'll see this code that defines the taxonomy_vocabulary entity type:

$return['taxonomy_vocabulary'] = array(
  'label' => t('Taxonomy vocabulary'),
  'controller class' => 'TaxonomyVocabularyController',
  'base table' => 'taxonomy_vocabulary',
  'entity keys' => array(
    'id' => 'vid',
    'label' => 'name',
  ),
  'fieldable' => FALSE,
);

The important bit to note is 'fieldable' => FALSE...that's why it's 'forbidden' to add fields to that type.

The taxonomy_term entity type is fieldable so you won't have any problem adding field instances to one of those.

If you really want to add a field to the vocabulary, you'll need to implement hook_entity_info_alter() to change the vocabulary entity to 'fieldable' => TRUE (I've done it before, it's perfectly safe):

function MYMODULE_entity_info_alter(&$info) {
  $info['taxonomy_vocabulary']['fieldable'] = TRUE;
}


Any way to edit Term Page? When I click a Term (such as "Garden Accesories"), I get some kind of a blog list with all the content associated with the term. I fear it might cause content duplication (it copies whole texts from different parts of the site). Is this fear rational?, and if it is, is there any way to control it (without Views)?

Thx.

It is default behaviour to show content tagged with that term. It does not copy content, it just runs a SQL query against it. You can control it easily by activating the view 'Taxonomy term' that is installed but inactive. Through that view you can more easily control how the associated content is displayed.

There are also various hook and theme functions that you can implement to change the output, such as hook_taxonomy_term_view_alter, template_preprocess_taxonomy_term etc.

Look at this post for more detail on that: Custom taxonomy term pages

There might be situations where you do not want your taxonomy terms to be links (to similar content tagged with that term). In that case you can set the field display formatter (which is link by default) to plain text.


How to set one variable for each link on a views un-formatted list I'm trying to create a variable to put in a l() function. It's the $rellink below.

<?php print l('', "$rellink", array ('html' => TRUE)); ?>

I have a list of content nodes I'm displaying in an un-formatted view. I want $rellink to be the link for each of them. So on item 1, it's the link to item 1. On item 2 it's the link to item 2 and so forth.

In the unformatted.tpl.php file I can print out

<?php print $view->style_plugin->row_tokens[$id]['[view_node]']; ?>

Which will print the correct link. But I need this inside the link part of the l() function and when I copy and past it in, it doesn't work.

So the question is, what have I done wrong there or if that's not possible/bad practice how do I set-up a variable in my preprocess function that I can use instead?

I've tried this in the preprocess funtion:

$view = $variables['view'];
$rellink = $view->style_plugin->row_tokens['$id']['[view_node]'];

But it doesn't recognise the global $id variable and I get an un-defined variable rellink variable warning anyway.

I accidentally left the quotes in when entering the variable path so it didn't work. I was entering:

<?php print l(' a', "$view->style_plugin->row_tokens[$id]['[path]']", array ('html' => TRUE)); ?>

And the I should've been putting in:

<?php print l(' a', $view->style_plugin->row_tokens[$id]['[path]'], array ('html' => TRUE)); ?>

When you're calling a value in an array, it won't work if you put the path in quotes.


Config entities and views integration Do Config entities have views support? What I have:

ConfigEntity which have fields: id, admin_label, display_label, config_options.
ContentEntity with fields: id, entity_config_id, author.
entity_config_id is an entity_reference to ConfigEntity entity.
I use views to show all ContentEntity entities and I outputted fields: entity_config_id, author.

What I need:

I want to output in views with ContentEntity some additional fields from ConfigEntity(e.g. display_label). But I can't do it, because I don't see any way how to integrate ConfigEntity with views.

No, there is no views integration for config entities (that's the term you mean, not entity configuration).

The easiest way to achieve what you want is to write custom custom views field plugins and define it in a EntityViewsData class for your entity and then just access the config entity and render what you want.


Using views_embed_views() to generate content for an email message. How can I get it to insert images and urls correctly for this purpose? I am using views_embed_views() to generate content for an email message. How can I get it to insert images and urls correctly for this purpose?

Or, asked another way, how can I put the contents of a view into an html email body?

Use hook_mail and drupal_mail to send out e-mail. drupal_mail at the place you want to send to mail, eg. hook_cron. And hook_mail to set the content. Use drupal_mail to send parameters to hook_mail.

As for the images, make sure that you use absolute url's in views (setting on the image field).


How to set width to Media entity image in CKEditor I have installed Media entity image Module with Lightning Distribution.
I can embed image through CKEditor. But how can I select image-styles for Image witch has embed.

Embedded code in CKEditor

<drupal-entity data-embed-button="media_browser" data-entity-embed-display="view_mode:media.embedded" data-entity-type="media" data-entity-uuid="869dbc6e-de17-4051-8945-e7acd3237c73"></drupal-entity>

Rendered in html

I found solution for my self.

Move to /admin/config/content/embed/button/manage/media_browser
Check to Thumbnail in Allowed Entity Embed Display plugins section.
In node editing select 'Display as Thumbnail' and you could select Image style.


Problems with Services and CSRF token I've been trying to create a user via webservice without doing any custom coding or curl.
This post got me 75% there: How to create test_endpoint?

I finally got it working, but only by passing in my creds with each request.  CSRF token header is ignored.

I'm using the Services and Services basic authentication modules.

I do an initial GET request to services/session/token with Basic auth headers with my username/password and get the token as expected.
In the next call, POST to rest/user, I have the CSRF token (HTTP_X_CSRF_TOKEN) and Content-type (application/json) and json encoded user data in the body.  Instead of authenticating with the token, I get a login popup.

If instead I send the Basic auth headers with my username/password along with the create user request and json data, it works.  I don't understand why CSRF is being ignored.

Thoughts?

Edit:  One other note.  In testing I used both the FF RestClient and FF Poster plugins.  I have not tested on Chrome.

For future users, there's a bunch of confusing examples out there. Based on the above link example this is my working setup:

URL: /rest/user.json

Headers:

"X-CSRF-Token":"fsddfhbusoibdfbdsbfoubewbfw"
"Content-Type":"application/json"

Body:

{
 "name":"username",
 "pass":"password",
 "mail":"email",
 "field_user_full_name":{"und":[{"value":"CHECK1 n CHECK2"}]},
 "roles":[4],
 "status":"1",
 "language":"und"
}


Is it possible and reasonable to convert a complicated, heavily styled html page into an editable Drupal site page? I already read this:

How to convert an HTML website to Drupal 7 nodes?

and this:

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

and some more.

Hello,

I have been tasked with creating an editable version of an html page that is heavily based on this template's design:

http://themeforest.net/item/zayra-bootstrap-3-retina-app-landing-page-/full_screen_preview/8135956

http://themeforest.net/item/zayra-bootstrap-3-retina-app-landing-page-/8135956

(not trying to advertise, just to give an idea)

I have read and learned about Drupal in the past week and have reached the point where I feel comfortable:

Tweaking themes.
Adding articles, polls and such plain content.
Messing around with the admin panel.

I don't understand how one would add content that is less "straight forward" to a Drupal site. Is it reasonable to do? Can it be done more easily with other CMSs (like Wordpress)? Should I tell my boss that the CMS should be used for news and articles in other areas of the site but NOT this specific promotional page?

From what I read I realize that I could create a rather complex view and a gazillion nodes and use that to generate an editable promotional page that looks like this template. My concern is that it may turn out unfriendly to the content professional.

I really would like to hear some expertly advice on how reasonably doable the task of creating an editable version of the promotional html page is in Drupal (that looks like the original).

You can use drupal to develop and complexity of site including that of a complex css design.  I personally work for a digital agency and every single project I have been on has been built in drupal and has been heavily design oriented.  I have also built JS apps in drupal as well.

If you are looking for a theme out of the box then you probably wont find it as they are generally free and not a whole lot of design into them.  If you are comfortable or willing to learn to create your own theme and template files then you most certainly can do this inside drupal.

It all depends on your level of knowledge and effort.

Here are a few heavy sites designed in drupal:

http://www.elmwoodreclaimedtimber.com/virtual-showroom (js app, but the site is also built on drupal)

http://www.servicesource.com

http://www.jedunn.com

http://www.tnvacation.com/made-in-tennessee

With drupal you have CSS, PHP, and MYSQL which means you can do anything those technologies can.

EDIT***

Also to answer your question more specific it really depends on how much of the content will be editable.  Drupal provides a more flexible GUI type layout called panels and panelyzer that provides more of what you may need.  Research into Panopoly distribution as its geared more towards landing pages


How to use kpr() or dsm() when i am not logged in I need to access my login form array using kpr() and dsm() functions but it's not working when I logged out from the site. How to debug and access the login form array as logged out.

You need to grant the Access developer information permission to the anonymous user role.

Be sure to revoke it again before releasing the site, it's an easy way to leak sensitive information.


how to do node preview validation? It is possible to set a Submit function for Preview button in an add/edit node form.

I would like to see if there is a possibility to go one step backward and validate the data to be previewed.

I just and only need to know how to have access to the validation hook for Preview button. (I don't need Submit hook! I only need Validate hook for this button)

There is no difference between Form Submit button's validate hook and Form Preview button's validate hook.

If you set the form's validate hook in HOOK_form_validate, you have set a secondary validation hook (it means if the default validation hook is passed, then it's the turn of the one you have set) which can be used for both Submit button and Preview button:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
   $form['#validate'][] = 'XYZ_validate';
}


/Drupal/ Stopped working I'm running a apache2 server on Ubuntu. While I was in the middle of configuring new content on my local instance of drupal via Firefox, the site suddenly stopped working. My first thought was the the apache2 server was down, so I restarted it. Then I created an index.html, and index.php that both worked (outside the drupal directory).
Now let's say I go to localhost/drupal/ I get a blank page. However, if I go to localhost/drupal/update.php I get the update page. I found that out as I was trying to figure out if any page would load. /index.php does not work.
Any idea to what I should investigate next? What's weird is that I was in the middle of working on the site when it went down. I don't see a reason for that to happen.
Any help is appreciated.
Thank you!
Update: I found that apache log can be handy.
By typing into the terminal:sudo cat /var/log/apache2/error.log
I found that the log had the following error:
PHP Fatal error:  Cannot redeclare class QueryConditionInterface in /var/www/html/drupal/includes/database/query.inc on line 16

I tried replacing this file with the file from the original drupal package, didn't work. Nor should it have because I didn't change any code in this file.
Things I've tried:

Restart mysql and appache2 using sudo service mysql restart

Delete /drupal/includes/ and re-populate it with files from the original
package.

Sounds like it can't connect to the database any more if it's crashing on /query.inc

Some things to try:

Check your database daemon is running (sudo service mysql status or similar)
Check that your settings file has the correct db information and permissions
Check that your drupal user in mysql has right level of permissions (and that it exists)


Why does user column name has UNIQUE Constraint? I got aware that the column name in TABLE users has a UNIQUE Constraint, when I tried to register a 2nd user with the same username : it returned a `integrity constraint violation 1062 duplicate entry '' for key 'name'.

Lets' say 2 of my customers called "John Doe" want to create an account : Ths 2nd one could not then ?!

So I made a quick SQL fix

ALTER TABLE `users` DROP INDEX `name`

I'd like to be sure it's not a very bad idea for some reasons ?

Config : this is a Drupal Commons distro

It's a bad idea, your are modifying a core feature of Drupal that others module (and the core itself) may relay on. That's the reason why that column has 'UNIQUE' option, because Drupal requires unique username. Think on user login: how you can login with different users if the have the same username?

Check this answer where you may find more info:
Is it possible to allow duplicate usernames ?