How to load certain old submission value into webform? I collect data in a web form.
As one of the first fields, it has a dropdown with which it selects a certain ID.
Later on, there shall be grouped elements like this:
value_old | value_new | diff

value_new is just the new value, that the user shall provide.
diff is the computed difference value_new - value_old and I think that I can implement that as a "Computed Twig" element.
value_old is a bit more complex.
This should be the value_new from the newest submission already in the database for the same form, where the ID from the dropdown in the beginning was the same.
I think, the solution should go in a direction of a token definition for the value_old or so, but I'm not sure on whether this is a) the right direction and b) how this could be done.

Long story short:
I wrote a custom webform element that takes an argument that gets updated via AJAX and queries the database.
Long story:
As in my comment, adding the "Webform View" module worked besides the wrong version number in the project description for the dependencies.
But it didn't help.
So, here are a few learnings along the way that might be interesting for people with similar challenges, followed by the final solution.
I was able to create a view that outputs the value_old that I need, when I provided the previously selected ID as an argument.
But:
While there is a webform element that shows views and takes arguments, it doesn't work with a token as an argument to reload it's content, when there is a (new) value for the token.
It is even not possible to split it up into several pages, such that there is already a value for the token, when the user proceeds to the next page.
I needed a webform element that gets recalculated, when the form changes, but gets its information from the database.
So, I created a new webform element in a custom module.
I took the „Computed Twig Element“ as a starting point.
But instead of doing a computation, I took the input value as an argument for querying the database for my value_old.
In theory, it would have been possible, to use the view from above, as long as computed values in this view are stored in the database.
If they aren't, querying the view will run out of memory.
In my case, there are some additional requirements to the rights management.
Therefore, I tried different querying mechanisms.
In this custom field, it was possible to query the database directly and to query the view.
I also tried the Webform Query module.
But something in there seems broken, because this module produced a query with a wrong name in it, as soon as I started querying for ordered results.


Panels view settings - how to preprocess the 'more' link I have block views added to a panel, and the panel is set to display the 'more' link. How can I change the text for this link?

Change the text of the link in the views module. On your views block admin page. Click on more link and change text there


Field Class Dependencies The question is pretty straightforward. How can I add a class on field A, if field B is empty? I can not find any module does this feature. The Conditional Fields does not have the class feature too. Can this done by programmatically? If so, how?

One solution here is is to use template_preprocess_field function. In your template.php add a MYTHEME_preprocess_field function and perform a check on the node's field value to determine a class that you set in the classes_array variable.

function MYTHEME_preprocess_field(&$variables) {
  $node = menu_get_object();

  //Add a new CSS class to field_MYHIDDEN_FIELD
  if($variables['element']['#field_name'] == 'field_MYHIDDEN_FIELD') {

    //Check field_MYCHECKED_FIELD for an empty value
    $new_class = (!isset($node->field_MYCHECKED_FIELD[LANGUAGE_NONE][0]['value'])) ? 'mytheme-field-novalue' : 'mytheme-field-value';
    $variables['classes_array'][] = $new_class;
  }
}


How to prevent node creation using hook_node_submit? Could you clarify me, how can I prevent node creation if I use hook_node_submit ?

What should I do in code of the hook for it ?
Do returning false ? Or throw an exception ?

That is, if some condition is true then the node simply does not create, without output of any error message.

To stop a node being created, you need to implement hook_node_validate instead, and raise an error. The hook is specifically to:

  Perform node validation before a node is created or updated.

Which is what you want.

The example in the docs page is probably quite close to what you'll need:

function hook_node_validate($node, $form, &$form_state) {
  if (isset($node->end) && isset($node->start)) {
    if ($node->start > $node->end) {
      form_set_error('time', t('An event may not end before it starts.'));
    }
  }
}

For the record, hook_node_submit is both conceptually the wrong place to try to stop a node being created, and too late in the process to do so anyway. The node hasn't been saved by that point, but you've lost any simple opportunity to stop the remaining submit handlers running and the default process completing. Even if you found a way to short out that functionality, there would be no sensible method to feed that back to the user.

You can throw an exception or kill the page request of course, yes, but Drupal obviously won't be able to recover from that and the request will terminate.


How to hand over value of field 1 to class array of field 2 programmatically in .theme Motivation

Context between template variable arrays is an old problem already known in D6 and 7 on theming level. What about D8 now? Any light on the horizon? Any chance to make this avaible without using Views module tweaks and work arounds?

Let's use an example:

Default standart content type Article has 4 input fields:

label (title)
body (main text area)
image
tags (terms, entity reference)

This content type also has an alternative Manage Fields Display setting for the Teaser view mode, where the image field formatter is set up using a smaller Image Style and with the option to link to the file or full node page. This creates an  element with url but without title or any other attributes around the Article image markup in Teaser view mode.

The question:

How can I hand over e.g. the first value of the tags (input terms) programmatically to a classes array of the wrapping  element?

In node--view--frontpage.html.twig this ...

`<a href="#" class="image icon fa-{{ (content.field_tags['0']['#title']) }}">{{ content.field_image }}</a>`

... works. Sure, because we grab it from the page variable. But image-formatter.html.twig is deeper nested inside the whole template system and it would be an overload to have the whole page variable array available here. Of course it is not there.

My assumption was to use the following preprocess functions:

function theme_preprocess_field(&$variables) {} and or
function theme_preprocess_image_formatter(&$variables) {}

The problem:

It seems - even if _preprocess_image_formatter has been suggested in the twig comments of the image-formatter.html.twig - there is 1.) no place to pass a string to any kind of attributes array for the  element in this twig file since the array has no given place for that. 2.) The hand over. How? Global vars are mostly not the best solution.

The core template code of image-formatter.html.twig:

{% if url %}
  {{ image }}
{% else %}
  {{ image }}
{% endif %}

The drafted alternation to demonstrate the needed effect:

{% if url %}
  {{ image }}
{% else %}
  {{ image }}
{% endif %}

NOTE: adding values manually and directly in the twig theme file like

{{ image }}`

shows that this is the right twig template. But it seems there is no way to get other values handed over (here), since _preprocess_image_formatter $variables array doesn't know any values of other fields of course (like of tags term field). And _preprocess_field() doesn't reach the image formatter level so that an addition to the attributes array rather affects the surrounding div but not the  element.

Context between template variable arrays is an old problem already
  known in D6 and 7 on theming level. What about D8 now? Any light on
  the horizon?

No, there is no light on the horizon, quite the contrary. Because of the concept of nested render elements, that are rendered independently. In D8 it is getting far more complicated because of the dynamic cache. And it wouldn't work at all with the plans for the future with placeholders and lazy building.


Missing 'Input format' On my inherited Drupal 6 site when I go to edit or add a news story 'Input format' is available for the Teaser, but not for the Body. I would like it for both or if it can only for one, have it on the Body so that I can choose an option such as 'Full HTML' so that images display. How do I achieve this?

check your CKeditor settings in the following path:
yoursitename/admin/settings/ckeditor/editg
If you find anything related to this
"your content type@node/add/your content type.edit-body" in the "Fields to exclude/include: " textarea, just remove.


How to configure role to edit only specific nodes by field? I have a content type named "Event". I created a field named "Type" so I may create different kinds of Events (eg. Courses, Lectures, Conferences).
The problem is that each type of Event is administered by different people. And one is not allowed to edit other's content.
How is the best way to do this?
Or is it better to create a content type for each type of event?

This looks like an ideal case for one of the Taxonomy access modules.

There are several to choose from, though I favour
Taxonomy Access Control Lite as it also allows you to grant access to individuals (should the need arise) as well as giving access rights based on roles.

The basic setup would be:-

Create a Taxonomy of the different kinds of event that you wish to use.
Give each "Event" node a Taxonomy reference field, that references the values from the Taxonomy that you setup in step 1.
Install and activate Taxonomy Access Control Lite via your preferred method.
Configure the access for each role to the Taxonomy from step 1. via the TAC lite configuration screen.  There are options to control the viewing, updating, and deletion of nodes, as well as the visibility of the Taxonomy terms in selection lists - which prevents users creating nodes tagged with event types that they don't have access to.

I hope that helps.


How do I replace the SQL query of a view? I need to override an SQL query of a view. I'm using Drupal 7 and Views 3.x-7.x-alpha1.

I understood I can write my own query with views_pre_execute. I followed the instructions mentioned here: http://blog.raisedeyebrow.com/2010/04/rewrite-a-views-query/.

I added this piece of code to my custom module.

function alterquery_views_pre_execute(&$view) {
  dsm($view);
}

Following the instructions, when I look for the value of $view->build_info['query'], I see that the type is object of a class SelectQuery.

How am I able to get total control of the query and use my own select statement?
I know that with hook_views_query_alter() I can modify a keyed array, but I would rather write the select statement from scratch.

Well, nothing is stoping you from building your own SelectQuery object and replacing the existing one. Overriding the query plugin is also an option. In this case it would be best to know WHY you're trying to replace the whole query. It makes very little sense to me.

Also, you're using alpha1? Why? That code is four and a half months old. Before attempting anything else, please update to -dev.


Which hook is invoked when pressing the remove button with widget image? In a content type named "R" there is a image field say "I". When a node with R->I is filled with a image file then standard you can remove this by pressing the remove button.  The standard images widget is used in drupal 7.

When I press this remove button something is executed as I get a message just 2 cm above the field "I" which is displaying the following message:

  content_type_name, content_type_title has been updated.

How do I find out which hook is invoked?

This message is coming from node_form_submit.
That function subsequently calls node_save which in turn calls the following hooks:

// Let modules modify the node before it is saved to the database.
module_invoke_all('node_presave', $node);
module_invoke_all('entity_presave', $node, 'node');
...
module_invoke_all('node_' . $op, $node);
module_invoke_all('entity_' . $op, $node, 'node');

where $op is one of 'update' or 'insert'.


How do I avoid duplicates when using a reference field? I have a content type with an entity reference field. If I have more then one entity in this field, and display the field in a view, it displays  duplicates.

Anyone figured out how to remove these duplicates in Drupal 8?

I removed the duplicates using hook_views_pre_render().

function hook_views_pre_render(\Drupal\views\ViewExecutable $view) {
  if ($view->id() == 'my_view_id') {
    $filtered_nids = array();

    foreach ($view->result as $key => $row) {
      if (in_array($row->nid, $filtered_nids)) {
        unset($view->result[$key]); // remove the duplicate
      } else {
        $filtered_nids[] = $row->nid;
      }
    }
  }
}

Probably not the best solution, but it works for my case.


Adding Contextual Links to Ctools Custom Content Type Plugin Ctools custom content type called Custom Panes shows contextual links when you have access permission and you hover over the pane (much like a block shows the contextual links) which allows you to easily configure the content of the pane.  After creating my own plugin that is similar to Custom Panes content type (with a few custom fields), I noticed that I do not have contextual links when I hover over my custom panes. I'm wondering if I can set that in the $plugin definition to show contextual links or what the work around would be.  I found the template function the panels uses to template_preprocess_panels_pane(&$vars) which actually looks for $vars['content']->content['#contextual_links'].  I'm wondering if there is a way to add contextual links to custom ctools content type plugins?

Any advice would be great!

You don't need to do that, what you can do is you can implement a hook_menu_alter and do this.

function YOUR-MODULE_menu_alter(&$items) {
  $items['YOUR-PLUGIN-PATH/%ctools_export_ui/edit']['context'] = MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE;
}

and then add your contextual link to your object. If it a block you can add below code in to your hook_block_view.

$block['content']['#contextual_links'] = array(
  'YOUR-CUSTOM-PLUGIN' => array('YOUR-PLUGIN-PATH', array($delta, 'edit'))
);


duplicate all instances of a term I'm trying to "clone" all nodes of a certain taxonomy term and assign them a new taxonomy term so they can function as sections of my site.

I'm making a site where i should put all of the information of a group of careers, something like: Contact, procedures, mission, syllabus, etc. (each on a page).

The thing is: the site should host like 16 different campuses, and about 150 careers. I'm using campus as a taxonomy term so i can group all careers of a campus, and i'm using another term to group every page of a certain career.

I don't want to create EVERY page of all of the careers, and i'm thinking there should be a way to duplicate a blank set of pages of a career and do a "batch duplicate".

I would appreciate any information that can point me in the right direction.

Thanks in advance.

I'm not sure I'm understanding this well, but perhaps you could create a new Content Type that holds all the career information that's common to all campuses. Then create a Content Type for each campus that has an Entity Reference field with unlimited cardinality (meaning that it allows you to have references to an unlimited number of careers). You can then create Views of campuses OR of careers with a relationship to the other Content Type, which will allow you to display the other Content Type fields in your table or list of nodes.


Ajax form add library on callback I'm having an AJAX form, which on submit fires a callback function where I want to attach my library.
Here's the submit button:
$form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => 'Submit',
    '#button_type' => 'primary',
    '#name' => 'calculate',
    '#submit' => ['::submitForm'],
    '#ajax' => [
      'callback' => [$this, 'submitFormCallback'],
      'wrapper' => 'my-form-id',
    ],
];

When the submitFormCallback is called I attach my library using AjaxResponse and its addAttachments like this:
$ajax_response->addAttachments([
  'library' => ['my_module/library_name']
]);

The problem is when the AJAX is completed the whole page's layout is destroyed. When I do NOT attach the library to AJAX response everything seems to work fine. (I've already tried to empty my JS files in my_module/library_name so the javascript won't affect any DOM elements, but the result is the same.
Is there any problem with the way I attach the library to AjaxResponse that may cause the broken layout?

Is there any problem with the way I attach the library to AjaxResponse
that may cause the broken layout?

I guess so. This is how core does it when its an AJAX response, it attaches it to the form like this:
$form['#attached']['library'][] = 'my_module/library_name';
$ajax_response->setAttachments($form['#attached']);


Getting error on installing bootstrap subtheme? Why i am getting this error "Unable to install bootstrap_subtheme, THEMENAME.settings has unmet dependencies". ?

Also my themename.theme file showing error on renaming "The item could not be renamed." for removing this error i created a clone blank file with name bootstrap_subtheme.theme and copy content of original themename.theme file ,paste it into the bootstrap_subtheme.theme file and finally deleted the original themename.theme file.

Still i am getting the following error Unable to install bootstrap_subtheme, THEMENAME.settings has unmet dependencies.

I was getting the same error message and here's how I fixed it.  In your subtheme folder (docroot/themes/bootstrap_subtheme) there's a config folder with two subfolders: install and schema.  Each of these subfolders has a YML file with THEMENAME in the file name, I just changed THEMENAME to my subtheme name and then I was able to install my subtheme.


How to set Cron Job in custom module for specific time in Drupal 7 I am building Drupal 7 Custom Module, my module needs to have cron job running on specific time, instead of the default cron time. How do I implement this?

This is my code for cron :

function mymodule_cron() {
    mymodule_data_process();
}

You can't. Drupal 7 does not provide this functionality. You have two options:

In your mymodule_cron(), test if it is after specified time, and at least arbitrary number of hours after previous run (like, 20?). That way your processing will run almost every day, no earlier than specified hour.
Make your module require Elysia Cron and use it's scheduling capabilities. That way you will get your code executed everyday, at specified time (5 minutes resolution if Elysia is configured as suggested in their documentation).

Important: You cannot assume your task will be executed at specific time. It will be executed at first opportunity after the time you specified, whenever, if ever, such opportunity happens. Elysia Cron is pretty good at it, true, but exact time of execution can't be assumed guaranteed. Highly probable, to some resolution, maybe. But never guaranteed.


Dynamic Select Query On Another DB Is there a straightforward solution to do the dynamic select statements against another database on the same server? I fooled around with attempting to modify the documentation example to no avail.

// Create an object of type SelectQuery and directly
// add extra detail to this query object: a condition, fields and a range
$query = db_select('custom_module_db', 'table_foo')
  ->condition('table_foo.id', 0, '>')
  ->fields(array('id', 'field_1', 'field_2'));

$result = $query->execute();

My current database setup looks like this

AWS RDS Server
 ->production drupal database
   ->Drupal Installation Tables
 ->custom module database
   ->Custom Module Tables

Clarification the below method works fine against the custom module database without adding a specific settings reference for that particular database.

So was looking to see if I can use the db_select() function in the same way as db_query() without needing to go in and add another database reference.

 $data_set = db_query($query='SELECT * FROM custom_module.db.table_foo WHERE ......)

Then grabbing the resultset by

$results = $this->WeightedAverageFunction($data_set->fetchAll())

Add external database name in settings.php(../sites/all/default/settings.php) file of your project. You can set databse in settings.php as follows:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'drupal_db',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '8080',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),

  'external' =>
  array (
    'default' =>
    array (
      'database' => 'external_db',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '8080',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

And you can directly add your query in files.


How to find elements in a render array I just spent a lot of time finding an element in a render array. I usually use dpm() to print the array, and then expand the options until I find what I'm looking for.

On larger arrays that's cumbersome. When I use print_r(), I can do a text search, but then it's hard to see the structure of the array and find the path to the element.

What other methods can you suggest?

There is extension module for Devel: Search Krumo. It uses Javascript to find text in Krumo/dpm messages and open array in those places.
Looks like this:

Update

After 22 Apr 2012 you should use sdpm() function to see search box.


Set a numerical field to perform Views Global Math Expression calculations Lets say I have three fields:

Field1 (a decimal)
Field2 (another decimal)
Global Math Expression

And in Global math expression I want to calculate [field1] + [field2]. How do I force Views to understand the replacement fields used in this global math expressions as numbers for calculation? As it is, it always returns the value 0.

Another solution that worked for me is to "Strip HTML tags":
Rewrite results --> [x] Strip HTML tags


How to trigger the click on the field collection button "add another item" using jQuery I want to trigger click on "Add Another item" button of field collection on some jQuery event.

jQuery('.field-add-more-submit').mousedown();

works in Inspector.

$('.field-add-more-submit').mousedown();

probably works from a module.

.click() doesn't work for some reason. More info here.


Unable to connect to local MySQL db using drush sql-sync I'm attempting to use drush sql-sync to sync my prod database to my local dev copy, and everything seems to work until drush attempts to log into the local MySQL. When it does, it throws this error:

"ERROR 1044 (42000) at line 39: Access denied for user 'drupal_user'@'localhost' to database 'mydb'"

I'm using a group alias file (e.g. mysite.aliases.drushrc.php), and I have my two aliases defined like so:

$local_sites = '/Users/steve/Sites/';
$aliases['local'] = array(
  'uri' => 'default',
  'root' => $local_sites . 'mysite/public_html',
  'path-aliases' => array(
    '%files' => $local_sites . 'mysite/public_html/sites/default/files',
    '%dump-dir' => '/Users/steve/Sites/mysite',
   ),
);

$aliases['prod'] = array(
  'uri' => 'default',
  'os' => 'Linux',
  'root' => '/cluster/www_system/www/www.mysite.org/current_build/public_html',
  'remote-host' => 'control.cphwf01.local',
  'remote-user' => 'sedwards',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
    '%dump-dir' => '/scratch',
   ),
);

I run sql-sync with --verbose, and I can see the file created on the remote server, and then copied to my local.  However, where it fails is at this line:

Calling system(mysql --database=mydb --host=localhost --user=drupal_user --password=mypass --silent < /Users/steve/Sites/mysite/mysiteLeW4G5);

If I paste this command to the command line like so:

mysql --database=mydb --host=localhost --user=drupal_user --password=mypass

it connects just fine. Now, I do notice that the temp dump file is then deleted, but it's there at the time sql-sync is attempting to connect.  Any ideas why this would be failing?

On a side note, what flag do I need to pass to sql-sync to get the dumped file to persist on my local once it's been created? That way I can test w/o having to dump from the server every time. It would also be way to just dump from the remote to my local w/o actually importing into the local db.

Thanks.

EDIT: I've run sql-conf for my local site (with --show-passwords) and it shows the correct information for the local copy.

EDIT 2: Following the advice here, I used the root user, and the sync worked.  However, this still doesn't make sense, since using the drush generated connection string with the db user/pw from settings.php at the command line works fine.

I have faced the same issue.
My solution was to add more rights to mysql user with this comande line :

GRANT ALL PRIVILEGES ON `myDB`.* TO 'mySQLuser'@'localhost' WITH GRANT OPTION

Because previous rights :

GRANT USAGE ON *.* TO 'mySQLuser'@'localhost' IDENTIFIED BY PASSWORD 'pwd'

Do not seem to be enough.


Cant display dropdown values on drupal commerce review page I have a some dropdown fields on on my commerce checkout page where the key is different than the value. I need this to be the case, because at checkout completion, I am submitting the values to an external database, and it expects the key value, not the display value.

However, I've found that the review page is listing the values (which is an uninteligble code and therefore useless to the user). I have not found a way to change this. If you inspect the array building the review page, it contains an array element 'data' which stores all the markup, and I see no way of modifying the display.

How can I display the dropdown keys on the review page?

EDIT:
To perhaps make this a little eaiser: by backtracing, I found that this function

customer_profile_type_ui/includes/customer_profile_type_ui.checkout_pane.inc:74:function customer_profile_type_ui_pane_review($form, $form_state, $checkout_pane, &$order) {

was calling this one

commerce/modules/customer/includes/commerce_customer.checkout_pane.inc:315:function commerce_customer_profile_pane_review($form, $form_state, $checkout_pane, $order) {

If you examine the code there, you will see that the review pane is being populated directly from the profile object, and the profile object is only storing the values (which makes sense). So, is there any way for me to obtain the keys?

You could use

hook_commerce_checkout_pane_info_alter

and set a different 'review' callback for the relevant checkout pane.

You can then control the output from your review callback.

See hook_commerce_checkout_pane_info for the option detail there.

You could also try theming the review page with

THEME_NAME_preprocess_commerce_checkout_review(&$variables) {} or
THEME_NAME_commerce_checkout_review(&$variables) {}


How do I display the user login in a popup? When menu item "Login" is clicked, I want to display the login form as a popup. How can I achieve this?

I have looked into the following but with little luck. (Let me know if the answer is below and I am missing it.)

modules: Overlay paths, Popup, Ajax login/register
Code: hook_admin_paths_alter()

Any help will be great. I am looking for a clean pop up option that I can theme too.

There is a module for that: Modal Forms. Enable and configure it, you're just a checkbox away from modal login :)


Unflag other users flag I have a site where people can sell their own items, so when a user creates a new product there is a flag "request product" that is added on the content.

I want the user who created the product to be able to unflag requests from other users.

Is this possible? Thanks

You could use the Rules module as it integrates very well with the Flag module.

Check out the Flag video series by Johan Falk. Part 7 is specifically regarding Rules.

In short you're looking to generate a list of users that have flagged a node and then with built in Rules actions, unflag them.


Howto theme list of nodes as item-list? I want to show a block with related nodes. The function getRelatedArticles() is a complex one and I can't build it with views. Is it possible to use the method viewMultiple() and output the list as item-list? If not, what would be the best practisce becide looping over the array and build the render array for each node? Something similar to the following code (which obviously does not work):

class RelatedArticleBlock  extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    $related_nids = $this->getRelatedArticles();

    $nodes = Node::loadMultiple($related_nids);
    $block['content'] = [
      '#theme' => 'item_list',
      '#list_type' => 'ul',
      '#wrapper_attributes' => [
        'class' => [
          'row',
        ],
      ],
      // I want to do something like:
      // '#items' => \Drupal::entityTypeManager()->getViewBuilder('node')->viewMultiple($nodes, 'teaser'),
    ];

    // I would like to avoid the following, build each node on it's own.
    foreach ($nodes as $node) {
      $block['content']['#items'][] = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'teaser');
    }

    return $block;
  }
}

viewMultiple() also optimizes the rendering process by returning a common #pre_render callback in the build array, see the discussions and linked topics here Twig: "for" does not display variable content without first displaying all variable content, so you can't put the output directly in #items.

So building each node on its own is the way to go and you probably won't find any differences in performance, because both methods result in the same caching mechanism.


Rules add date variable from webform submission I have a webform where the user also submits date. I would like to populate a date type field with the submitted date. I tried making variable by "Add variable", but I do not know how to access my webform submission.

Later I realised that I need to run a custom php code, so I wrote this, which actually works:

// use the submitted time value from the webform and convert it to time, also use it for an end date one year later
$time = strtotime($data['components']['submitted time']['value'][0]);
$time2 = strtotime('+1 year', $time);

//convert to date formats to the format used in these fields
$startdate = date('Y-m-d',$time);
$enddate = date('Y-m-d',$time2);

//update the field values and save the updates
$new_user_request -> field_start['und'][0]['value'] = $startdate;
$new_user_request -> field_end['und'][0]['value'] = $enddate;
user_save($new_user_request);

Hopefully this helps someone else too.


what is the strongarm variable addititonal_settings_active_tab_* I am using the Features and Strongarm module to move my work between sites. I am using them as a way of version controlling changes made in the database (as Configuration Management module has many issues.)

I am trying to understand what the following settings are, which module (or core) creates them, and should they be passed from site to site:

 additional_settings__active_tab_chapter
 additional_settings__active_tab_committee
 additional_settings__active_tab_document
 additional_settings__active_tab_event
 additional_settings__active_tab_jcr_article
 additional_settings__active_tab_jcr_issue
 additional_settings__active_tab_news
 additional_settings__active_tab_page
 additional_settings__active_tab_success_stories

The last piece of these settings ie: 'chapter' are the names of the content types on the site. Should I be passing these variables?

It is the vertical tab that is "active" when the node edit form loads. Export as needed (I usually don't).

FWIW, i used 'drush vget' to take a look at the variables value and that made it pretty easy to figure out its purpose. (Drush)


How to use titles instead of IDs in urls for nodes? I am managing a site right now (Drupal 6) and the links are all coming out in the form http://example.com/blog/12553.

I'd like these urls to be based on the name of the article. I could swear that the site used to do this, but not sure at all where to find this setting or what might have gone wrong. I was looking into 'clean urls' but conclude that the urls are clean (Because they don't have PHP parameters), but I'm not sure.

I'm pretty familiar with PHP and programming... less familiar with Drupal

You should check to see if the pathauto module is installed. If not, I highly recommend downloading, installing and enabling it... It should make very short work of this.

Here's the link for d6

https://www.drupal.org/node/17345/release?api_version%5B%5D=87

If it is already enabled... then you may have more trouble as the d6 version is no longer maintained... so you may need to do some troubleshooting of this module.


Same node to show using different themes Drupal 8 question:
I need to show same content page (say /node/12) using different themes, when used in a menu link. I have 'URLs aliases' created (eg:  /ma/testPage, /nj/testPage ) both points to /node/12 (URL aliases module).

I have 'switch page theme' module which points to different themes based on the path (/ma/* points to theme1,  /nj/* points to theme2).

When I view the page using /nj/testPage or  /ma/testPage, it uses the same theme (theme1). As per the rule in 'Switch page theme' i am expecting the same node render using different theme. It doesn't happen like that.  Could anyone help what i am doing wrong?
Or is it not possible to render same node using different theme?

The Switch Page Theme module not supported "switching by aliases" yet.

See details here Theme switching not working with aliased paths?


How to automatically create a node for each user and set the user as author of the node? I have 50 users on my site. I want to create 50 nodes and then set the author of the node to each of my 50 users.

Is there a way to do this using a module or programmatically, rather than having to first create all the 50 nodes and then editing the author fields?

Step 1

Use the Rules module to create a Rules Component, which includes whatever Rules Conditions you might need (if any), and with a Rules Action to Create an entity (of type node). Make sure to use a parameter (of type "integer"), and which you use as the value to be assigned for the "author" of the node to be created. Here is an example of such Rules Component (in Rules export format, if you have the Rules UI enabled you should be able to import it in your own site):

{ "rules_create_a_new_node" : {
    "LABEL" : "Create a new node",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "uid_of_author" : { "label" : "Uid of the user to be used as author", "type" : "integer" } },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "user", "id" : [ "uid-of-author" ] },
          "PROVIDE" : { "entity_fetched" : { "user_fetched" : "Fetched user" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "page",
            "param_title" : "Node created for user [user-fetched:name]",
            "param_author" : [ "user-fetched" ]
          },
          "PROVIDE" : { "entity_created" : { "node_created" : "Created node" } }
        }
      },
      { "drupal_message" : { "message" : "Node creation completed for user with name \u0022[user-fetched:name]\u0022." } }
    ]
  }
}

Some details about the above Rules Component:

It checks if the user using it, has role "admin" (just to be secure it a bit, feel free to omit that if you don't want that).
It fetched the info about the user for which the uid was entered as a parameter.
It creates a node of type (machine name) page (adapt that to whatever machine name fits for you).
It shows a Drupal message to confirm the node got created (just for testing, remove it if you don't need it anymore).

After you imported the above Rules component, use the "execute" link in front of this Rules Component to QA-test your component (for which you'll need to enter an appropriate uid value for the author you want). After it completes, it'll show an informational Drupal message similar to this one (with Demo.User = the name of the user for which I entered the uid):

  Node creation completed for user with name "Demo.User".

Step 2

Create a view of the group of users for which those nodes should be created. Then transform that view into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?". In doing so, you'll then be able to use the Rules Component from Step 1. Make sure one of the fields (columns) in your VBO view is the uid for each of the (50) users for which you want to create such node.

Tutorial

To get the idea, have a look at the video about Using Rules components with VBO" which uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Attention: to process like 100.000 entities at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

PS: no need for custom code ...


How to bulk install modules from local machine? Is there a way to install multiple modules at one from a local machine?

I've seen quickupdate but that is not from a local install, and relied on FTP which I cannot use.

You can just put them in one zip file, and upload using Drupal UI just as if they were one. Drupal will store them together, in  subdirectories just as you packed them. That's all, never been a problem for me.

Perfect example is, well, Examples project: http://ftp.drupal.org/files/projects/examples-7.x-1.x-dev.zip one zip, many functionally unrelated modules.


Create a view to show comments on a user ONLY from that user Am using comment as reviews for a content type. Now am trying to create a block in views that will appear on the user profile page. I want to show ONLY comments (reviews) that are from the specific users page i'm on. If the user has no comments made, then the block would be hidden. What settings in views would allow this to happen?

I've tried using content filters and relationship filters but I haven't been able get the right settings. Example: Am on User A's Profile page, I want to display all comments from User A on his profile page.

EDIT: Since my answer really didnt receive anything that can help. I will try to better word the question. I just need to create a block with comments from a specific content type in context to the user profile I'm on. I've created my view and added a contextual filter base off the author uid. But it still shows all the comments not just the ones from the current profile user.

You should indeed use a contextual filter, selecting "When the filter value is NOT available", then "provide default value", and choose "user ID from loggued user".

That should work.


How to use hook_webform_submission_presave In webform 7.x-4.10 I created a module like this:

function webform_presave_webform_submission_presave($node, &$submission) {
  if ($webform->nid == 28) {
    $component_id = 1;
    $submission->data[$component_id]['value'][0] = 'Yes';
  }
}

My webform with nid 28 has only one field, a texfield with a default value to "No".

When the webform is submitted, the value of the field is not change...

What am I doing wrong?

Notice the value on which you check in the if.

the correct code is:

function webform_presave_webform_submission_presave($node, &$submission) {
  if ($submission->nid == 28) {
    $component_id = 1;
    $submission->data[$component_id][0] = 'Yes';
  }
}


Creating a view from multiple content types where one is optional Is it possible to display multiple content types within a view that may or may not have a related secondary content type?

I have two content types (A - which contains a title and body field, and B - which contains a title and body field). In this view, content type A will always exist - and I would like to have any related B content types display underneath the appropriate object. It is possible that no content B types will exist for that title, so if that's the case it can move on and display the next content A type info:

(A) Title = New York, body = "Something"
(A) Title = Ohio, body = "Something"
     (B) Title = Ohio, body = "An interesting tidbit about Ohio"
(A) Title = Virginia, body = "Something"
...etc...

Any idea how I may go about accomplishing this? I have heard about a References module to explore, but it seems like that would only pull data where that relationship exists, right? And that in my above example, although I would be anticipating three states in my view, references would only show me the Ohio one because that's the only one that also contains a content B type.

Is that correct? Or is my understanding incorrect?

Install the Entity Reference module, and create an entity reference field on your Content Type B. Configure the field to reference Target Type Content and Target bundle Type A. Lets call the field ref_to_a.

Set up a view of Content Type A as a table of fields. Add the Title and Body fields. Then under Advanced add a Relationship. Use Entity Reference: Referencing Entity and choose Content referencing Content from field_ref_to_a Do not set the relationship as required, as you do not want to exclude the Type A records which do not have a Type B referencing them.

Now add a Content:Body field to your view, and configure it to use the relationship you have just created.

This should give you a view which will look like:

New York    Something
Ohio        Something   Interesting tidbit
Virginia    Something

Adjust your formatting as required, and good luck.


How to create custom page with user images in grid and with pagination, not using views As I guess I need to override node.tpl.php or page.tpl.php?

use hook_menu() to create a path to your page. Then use db_select() with the tableSort extender to supply pagination in the hook_menu page callback. Select the uid, username, user image(s) ? in your database query.

Then just loop over your resultset and output a div with your user images per cell. Simply float all the divs to the left so your output appears as a grid instead of a single long column of rows.


Panels "Page not found" when using required wildcard argument I have a Panel Page, which displays several View Panes.  I have specified a term name as an argument in the path settings. This is used to filter the View Panes.

When I use an optional argument everything works fine - clinical-role/!role_name.  But when I change to a required argument clinical-role/%role_name then I get page not found when visiting /clinical-role and when visiting /clinical-role/early-skills-for-non-training-grade-doctors

I need the argument to be required because I don't want the panel to display when people visit /clinical-role.

Here is an export of the Panel Page: http://pastebin.com/ASmFnVU5

Here are my argument settings:

And also my context settings:

The problem was that my taxonomy terms had dashes, e.g. "Early skills for non-training grade doctors".  When used in conjunction with views contextual filters and the option to "Transform spaces to dashes in URL", it doesn't match properly, so no value for the context is provided.  This is related to the following views bug - https://www.drupal.org/node/672606 (no solution as yet for panels but there is a solution if you're just using a view page in comment #16).  My solution was to remove all dashes from my term names.  Not ideal but fixes the problem.

Here is how I set things up to pull a taxonomy term name contextual filter into a View Pane, in case it helps someone.  If anyone knows a better way to go about this then please let me know and I will update this answer:

View Setup - Contextual Filter

View Setup - Argument Input

This part is counter intuitive, you have to choose "No argument input".  Providing a context from panels will prevent the default filter value from being used.  Thanks to the following comment for helping me figure this out: Views contextual filters taxonomy name

Panel Setup

N.b you have to use a panel page here (structure > pages), so that you can make use of the wildcard feature.  I tried this by panelizing a node initially but couldn't get it to work.

Basic settings:

Argument settings:


Using views to display content comparing users id First of all, sorry for my bad english.

I'm using Drupal 7

Here is my problem :

I have a views in wich I would like to display a list of custom content type only for the users that I selected with a custom field "entity ID" in this custom content type.
This users share the same role, but they can't see the node of others users (of the same role or another role as well).

I taught the simplest method would be to add some PHP code thanks to the PHP views module, but if you have a better solution I'll love to hear that.

So this is what I made so far:

I added a global PHP in the filters criteria section of the view with this code:

global $user;
$current_user = $user->uid;
$destiny_user = $data->field_field_uttilisateur[0][raw][entity]->uid;

if ($current_user == $destiny_user) {
   return false;
} else {
   return true;
}

Basicaly I'm comparing the current user ID with the ID I filled in the content type.
If this "function" returns true, then the current row is not displayed.

I don't have to worry to know if the user is authentified because I already do that in Page settings (Access)

But it seems like $destiny_user is always empty. I don't get it because when I add an global php field in the fields section all seems ok (I can see the ID of the user I whant to display the row)

I'm using this method $data->field_field_uttilisateur[0][raw][entity]->uid; because the $rows->field_uttilisateur; is not working. (It display the nid Oo)
After some research I found this solution that seems to work... at least more than the other one.

I'm having a really bad time with this, do you have some ideas how I can get this to work?

Thank you in advance !

This can be achieved using contextual filters in views. Here are the steps:

In the views edit page click on Advanced section.
Click on the Add button corresponding to "Contextual Filters"
Search for your custom field in your custom content type and add it.
In the configure contextual filter which appears make the following changes.
Under "When the filter value is not in the url" section, select the option "Provide default value". In the type select list, select the option "User ID from logged in user".

Save the changes.


How to transfer multiple databases by sql-sync? I've created proper aliases and successfully pulled files/database from live to dev server by:

drush sql-sync @live @dev

But I noticed my secondary database (defined also in settings.php and in alias file) has not been populated when syncing. I have default database and one additional database for some special operations which I use.

There was no any error message after sync, so I presume drush did not try to copy that database.

Is there any additional procedure I must follow when doing sync of 2 databases, or this was presumed to be automatic?

If there is no out-of-the-box answer, or I should show my config files?

Drush sql-sync will only copy one database per run; if you have multiple databases to copy, you must run sql-sync multiple times.  Use --source-database=other and --target-database=other to specify some other database.  Use --source-target=mirror and --target-target=mirror if you want to copy a secondary mirror of your Drupal database (not your use-case).

Rename 'other' and 'mirror' to match the appropriate key of your database record.  See figure below.

Array
(
    [default] => Array
        (
            [default] => Array
                (
                    [driver] => mysql
                    [username] => www-data
                    [host] => localhost
                    [database] => drupaldb
                )
            [mirror] => Array
                (
                    [driver] => mysql
                    [username] => www-data
                    [host] => localhost
                    [database] => mirrordrupaldb
                )

        )
    [other] => Array
        (
            [default] => Array
                (
                    [driver] => mysql
                    [username] => www-data
                    [host] => localhost
                    [database] => otherdb
                )

        )

)

Update from NenadP:

It seems that you need to add --strict=0 when using Drush 5 to work around a bug in the sql-sync command definition.  This has been fixed in Drush 8.6-6.x.


Webform select limit Is there a method to limit the number of chosen select options?
In D7 there was Webform Select Limit but in D8 there is no alternative.

What I want to do is this:
Create a webform for event registration with maximum number op places.

NAME: ____
EMAIL: _____
WORKSHOP:
 A. Option 1 (maximum 20 places)
 B. Option 2 (maximum 20 places)
 C. Option 3 (no maximum)
 ....

SUBMIT

@see Issue #3076750: Add Webform Options Limit


Using ajax in my entityform I have a content type called Area and another content type called apartment that has a reference to area.

I have an Investment form (using entityform module) in which users select which area; after that, users should be able to see apartments in that area in a select box. (This feature should be implemented wit ajax.)

I want to have some filters on areas and apartments like views module filters (for example apartment which are not sold). How should I implement these features?

and here's my node--invest.tpl.php:

<?php $language = $GLOBALS['language']; if ($language->language == $node->language): ?>

                        <?php echo $custom_content['body'] ?>

                    <?php foreach($custom_content['panels'] as $panel): ?>

<?php echo $panel['title']?>

                                    <?php foreach($panel['steps'] as $step): ?>

<?php echo $step ?>

                                    <?php endforeach; ?>

                    <?php endforeach; ?>

<?php echo $custom_content['form_title'] ?>

<?php echo $custom_content['form_body'] ?>

                    <?php print drupal_render($entityform) ?>

<?php endif; ?>

And if you wonder what is $custom_content, this is the code that generates it.

function get_invest_page_data($node) {
    $invest = [];
    $invest['title'] = $node['title'];
    $invest['body'] = $node['body'][0]['value'];
    $invest['form_title'] = $node['field_form_title'][0]['value'];
    $invest['form_body'] = $node['field_form_body'][0]['value'];
    $invest['panels'] = [];

    if ( ! empty($node['field_step_panel'])) {
        $i = 0;
        foreach ($node['field_step_panel'] as $panel_key) {
            $panel = load_collection($panel_key['value']);
            $panels[$i] = [];
            $invest['panels'][$i]['title'] = $panel->field_invest_panel_title['und'][0]['value'];

            $steps_keys = $panel->field_invest_panel_step;

            $j = 0;
            foreach ($steps_keys['und'] as $step_key) {
                $step = load_collection($step_key['value']);
                $invest['panels'][$i]['steps'][$j] = $step->field_invest_panel_step_body['und'][0]['value'];
                $j++;
            }

            $i++;
        }
    }

    return $invest;
}

This code exists in template.php.
The following line is used in theme_prepreprocess_node().

$node['custom_content'] = get_invest_page_data($node);

The ajax from a form is handled by the form function itself wich is edited in the mdule layer, not in the template layer. The custom module approach would be.

Find the id of the entity form, see this Tutorial

Once you have the id you can use the MY_MODULE_form_FORM_ID_alter to edit the form elements to use ajax.
See this Tutorial for more info on ajax forms.

If you want the ajax callback to alter an external element/several wrappers you can use the ajax_command_* functions to change pretty much anything selectable by JS.
Have the ajax callback return something like this. (you won't need to set the #ajax wrapper in this case).

More about the drupal's ajax_command_* functions

function AJAX_CALLBACK_CALLED_FROM_FIELD($form, &$form_state){
  $commands[] = ajax_command_html('JQUERY_SELECTOR', 'VALID_HTML'); // Or any other valid ajax command.
  return array(
    '#type' => 'ajax',
    '#commands' => $commands
  );
}


How to display article from category and show it in block I have created a content type which has some fields, and I want these fields to be displayed as a block.

I need to display some article like 5 articles from category called sport news only.

how can i do that in drupal 7

Not sure of your exact need, between articles, your content type... Try something like that :

Go to admin/structure/views/add.
Fill in the form : Show Content of type article (or Your content type). If  sport news is a taxonomy category, tagged with sport news.

Uncheck create page, check create a block, display format table of fields, five items, then continue and edit.

Now in the left side of the form, click on add fields, choose the fields you'd like to display and settings for each field. Give a admin name to your block in Block settings, at the top of the middle column. You now have a block view with 5 items of content type article and the fields you selected.

Go to admin/structure/block, look for the block you've just created, and set the region where you'd like to display it, or click on configure to be more specific, displaying it on specific pages, for specific roles or whatever.


Views : Rewrite results - Edit content Is there a way to rewrite the content of a field displayed in a view?

E.g. If my title is long, like "[Product ID:5739] Ninja Stars" and I want it to display just "Ninja Stars" in the view, how can I do it?

You can in views rewrite the result of any field, or trim most fields, but if there is some logic to what you want to remove you would need to do with with a preprocess hook in your theme. In this case it sounds like you need to do the latter. Something like this should do the trick:

function theme_preprocess_views_view_fields(&$vars) {
  if ($do_your_checks) {
    $vars['fields']['field_name'] = preg_replace(...) // Use regular expression to change title.
  }
}


Does "Boost" module work together with "Theme Key" module? I wonder if the Boost module works together with the ThemeKey module.

Has anyone experience with both modules working together? Especially when it comes to different style-sheets for different devices.

The two work well together (Does ThemeKey supports Boost caching) with the caveat:

  ThemeKey supports page caching and external caches like boost - if the
  page is cachable.

  If you switch a theme depending on the user's browser, the page isn't
  globally cachable at all, because other users are using different
  browsers! That's not a ThemeKey issue.


Does it make sense to develop a fantasy sports management system by creating or extending entities? I am considering building a fantasy sports management system with Drupal. The system will need content, so that's taken care of with the standard Drupal system. However, does it make sense (or even possible) to create new entities that represent players, teams, leagues, stat-lines, etc?

I have built systems like this in the past (.NET) and it's difficult for me to wrap my mind around the idea of combining content nodes with players, teams, and stats. There are many fields that are exclusive to each type of node/entity and the sheer volume of players and stat data will push the node tables to crazy levels.

I haven't messed with Drupal 7 entities (which I believe abstracts nodes, users, and taxonomies), but I'd like to hear opinions if this concept is possible.

Drupal 6 has a module called League Site that might be useful to have a look at... I don't think it has been ported to 7 yet but it has an awful lot of functionality for league sports right out of the box.


Charging UserPoints for flagging a node with Rules in PHP I am trying to charge points for flagging a node with Rules in PHP, an I am using the following code.

 //Get variables and load user.
$uid = [userpoints-transaction:user:uid];
$account = user_load($uid);

// Check the user has enough points.
if ($loaded_points > 10) {

  // DON'T KNOW HOW TO TAKE 10 POINTS.

  // Flag a node.
  $flag = flag_get_flag('purchase') or die('no "purchase" flag defined');
  $flag->flag('flag', $node->nid);
  // Search for the newly created flagging entity.
  $flag = flag_get_user_flags('node', $node->nid);

  foreach ($flag as $flagging_object) {
    $flagging_id = $flagging_object->flagging_id;
  }

  // Load the entity found and create or update a field value.
  $flagging = entity_load_single('flagging', $flagging_id);
  $flagging->purchase['und'][0]['value'] = 'DONT KNOW DEFAULT VALUE OF FLAGGING';

  // Save the updated flagging entity object.
  entity_save('flagging', $flagging);
}

drupal_set_message($msg);

I don't know how to charge them 10 points and what the default value is when flagging a node.

When you simply want to grant 10 userpoints to a user after flagging a node, you're making things way to complicated! This can be done without custom coding at all. Here's what you have to do:

Create a new rule.
Add an event "A node has been flagged, under YOUR_FLAG".
Add an action "Grant points to a user" and give it an amount of 10.
Done!


SMTP Authentication Support address/from name overwritten by Site Information Pretty much as the title says really. I'm using the SMTP Authentication Support module to try and send account notification e-mails through our G Suite account. I've filled in a name and e-mail address in the E-mail Options section, but whenever I send a test mail it arrives from the e-mail address given in Drupal's main Site Information options, and without a from name at all.

How do I get it to display a from name in the e-mails it sends?

Using Drupal 7.67 and SMTP Authentication 7.x-1.7.

You can use the Mail System module to configure how to send different emails.


How to move a taxonomy term from one vocabulary to another? How can I change vocabulary of some taxonomy term? And keep all its data - tid, references, fields, alias and translations (except hierarchy)?

Term merge module seems to be what you are looking for. Just adding some features as is from its project page on D.O.

Updating term references in the field values, swapping values from the branch term to the trunk term. We support taxonomy term reference, entity reference, and any other field types that correctly define their foreign keys.
Keeping/Removing branch terms: you decide whether to keep or remove branch terms after the merge.
Merging field values: you can specify a list of fields and during merge the values of those fields from branch terms will be added to the values of the trunk term. This way you can keep field values of the branch terms after deleting them.

So all you'll need to do is to create a new term to that other vocabulary and do a merge with the old term from the other vocabulary. As for the tid I don't think that is possible to be kept or even if there is any meaning in trying to do so since all data will be transferred to the new term.


How to force drupal 7 to load HTTPS assets? Environment:
apache + ssl + domain access

Our drupal 7 site uses domain access multiple sub domains
our server is SSL enabled

if I do not set $base_url in settings.php then all of our assets our loaded via HTTP and the user receives a mixed content error

If I DO set $base_url users are redirected to the default subdomain (e.g. foo.blah.com) instead of their current domain (e.g. bar.blah.com)

My question is, how do I force drupal to load all assets via HTTPS?

That way I can uncomment the #base_url

I updated settings.php with: $base_url = 'https://'.$_SERVER['SERVER_NAME'];


theme_hook_suggestions on custom theme? I have a module that implements HOOK_theme() to define a 'petition' theme like so:

function mymod_theme() {
  return [
    'petititon' => ['variables' => ['foo'=>NULL], 'template' => 'petition']
  ];
}

Which I then use like:

$some_render_array[] = [ '#theme' => 'petition', '#foo' => 'Bar' ];

Which is then rendered by a petition.tpl.php template file.

However, I would like to do this:

$some_render_array[] = [
  '#theme' => 'petition',
  '#theme_hook_suggestions' => ['petition__1'],
  '#foo' => 'Bar'
];

...and have it look for petition--1.tpl.php, in the same way you can for nodes, pages etc.

But this doesn't seem to work. Is it possible to have a theme that can take a template suggestion? I have a bunch of things to render which all require the same processing but use different templates.

To suggest specific templates you probably need to do it in your theme's template file, use the hook_preprocess_HOOK where the first hook is the name of your theme and seconde HOOK is either page to suggest a page template or node to suggest a node page.

Here's an example

/**
 * Implementation of hook_preprocess_HOOK().
 */
function mymodule_preprocess_page(&$variables){
  // change the condition to whatever you like
  if(isset($variables['node']) && arg(2) != 'edit')
    $variables['theme_hook_suggestions'][] = 'page__'. $variables['node']->type;
}


Devel module and Krumo I super love Krumo/Devel. However, I'm sure I'm missing something obvious, because when I use dsm() and I get my array or object all expandable and awesome, sometimes I have a hard time knowing which array or object it is. At the top, it just says ... (Object) stdClass.

Is there somewhere that it includes the name of the object/array you're exploring? What about on the devel tab of a node?

Sometimes, if I need to differentiate between different debug items, I'll use something like the following:

kpr(array(
  'node' => $node,
  'comments' => $comments,
  'links' => $links,
));

Or, if debug items are split in different places, just simply:

kpr(array('user' => $user));


Drop-down select instead of selection box in custom field widget I am creating a custom field for phone numbers. The field creates a phone record that contains the type of phone contact (work, home, etc), as well as the number and an extension... much like Apple's "Contacts" app.

The problem I am having is for the phone type drop-down list. Instead of showing a nice drop-down select list like this example of a publishing status...

I end up with a selection box like this...

Here is what my hook_field_widget_info() looks like...

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

  $element['label'] = array(
    '#type' => 'select',
    '#options' => drupal_map_assoc(array(
      t('home'),
      t('work'),
      t('main'),
      t('mobile'),
      t('other'),
    )),
    '#size' => 12,
    '#default_value' => isset($items[$delta]['label']) ? $items[$delta]['label'] : 'home',
  );

  $element['number'] = array(
    '#type' => 'textfield',
    '#title' => t('Number'),
    '#size' => 16,
    '#default_value' => isset($items[$delta]['number']) ? $items[$delta]['number'] : '',
  );

  $element['ext'] = array(
    '#type' => 'textfield',
    '#field_prefix' => t('ext'),
    '#size' => 6,
    '#default_value' => isset($items[$delta]['ext']) ? $items[$delta]['ext'] : '',
  );

  $element['primary'] = array(
    '#type' => 'ckeckbox',
    '#default_value' => isset($items[$delta]['primary']) ? $items[$delta]['primary'] : 0,
    '#return_value' => 1,
  );

  return $element;
}

I can see how the selection box style select element can be useful for multiple selects, but this is just a single select. I'd like to see a drop-down element. I must be missing something here, but I haven't figured out what it could be. Any ideas?

Okay, I figured it out and it was much easier than I thought... It's the "size" attribute. I deleted the size attribute, ('#size' => 12,), and I have a drop-down select list. I suppose it just came to posting the question here for me to figure it out on my own. :P


How to access individual items in $form_state['values'] post-submit Question

After a user has a submitted a form how do I determine how to reference individual form field values in $form_state['values'] ?

Examples

For example, I have several fields in my form, such as 'field_organization' that would normally be accessed (for CSS) purposes, like so:

$form['customer_profile_billing']['field_organization']

I have others in my form that have even more convoluted paths such as

['und'][0]['another-name']['a-fourth-name'], etc.

You can access $form_state['values'] of a field in like

$variable = $form_state['values']['your_field_name'];

After saving you can access like this

$variable = $form['your_field_name']['und'][0]['value'];

For more information please check

$form_state keys
What is $form_state used for ?

Hope this will help you.


500 Internal server error I have a site running Drupal 7, and hosted on GoDaddy.

I use Filezilla FTP client to upload the files, or do any kind of file management on the server.

When I upload a file, the site shows a 500 error. After 25-30 minutes, the site starts working as usual.

This happens every time I upload a file.

I have this error number of times while refreshing or uploading modules.
it seems to be a server error. because some time server does not respond.


How can I let users enter the cck value once and then protect the field from editing? I have several cck fields that shouldn't be modified once after the node is created. For example like fields for gender, name, birth date and so on.
Is it possible to hide or make them unable to edit those fields by users after the node creation?   I thought maybe I could do that by Rules but unfortunately it seems that there is no action for hiding cck field forms though it has the condition for "if field has a value".

I think the link below will be helpful to you..

Code snippet: How to set the disabled or readonly attribute of a CCK field

Check this link and let me know if in case of any query.

Thanks.


Using Entity Field Queries with "does not contain"? I have an EFQ that selects all nodes with titles not equal to 'panda'.

$query = new EntityFieldQuery;

$results = $query
 ->entityCondition('entity_type', 'node')
 -> propertyCondition('title', 'panda', '!=')
 ->execute();

How would I go about changing this query to give me only nodes whose titles don't contain the word 'panda' at all?

The comments on the official documentation page for propertycondition() give an example using sql like on propertycondition().

From that example try the following change to your code:

   -> propertyCondition('title', '%panda%', 'NOT LIKE')

EDIT: I haven't actually tried this, just going offa docs and comments.


How to download the files data attached to webform I have webform with text fields and file upload field. How can i download the all the documents which was  uploaded through this webform.

You can do it by using these modules:

Webform Protected Downloads

  This module provides a handy solution for the following situation:

  you want to offer some files for download to either anonymous or    registered users
  you don't want those files to be publicly accessible
  you want to collect some data before granting access to the files
  you want to be sure that the user gives a valid email address

Webform2PDF

  The Webform2PDF Drupal module is an extension of the Webform module.
  It can be used to generate PDF document from the results of a form.
  The generated PDF document can be attached to the form summary e-mail
  sent by Webform module, or it can be downloaded from the /Results/
  page. Different PDF templates can be set for each form.


Rule on Saving New Comment not triggered I want to do some action after saving a news comment which needs comment's CID but I can not do anything after saving news comment!!

I have tested any other actions but none of them triggered by this action.

I have the same problem with the "after updating existing comment".

Only the "before saving comment" action works but I need comment's cid in my code and this value isn't set before saving a comment. So, how can I do my job?

I cannot reproduce this problem. Attached is an export of a rule which fires when a comment is added to an Article or when a comment on an Article is updated. The Rule simply prints a system message containing the CID so that you can see the Rule was able to access the CID. I have tested this and I always get the message, with the CID, when adding or updating a comment.

{ "rules_comment_added_or_updated" : {
    "LABEL" : "Comment added or updated",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_i18n", "rules", "comment" ],
    "ON" : {
      "comment_insert--comment_node_article" : { "bundle" : "comment_node_article" },
      "comment_update--comment_node_article" : { "bundle" : "comment_node_article" }
    },
    "DO" : [
      { "drupal_message" : { "message" : "Comment id = \u0022[comment:cid]\u0022" } }
    ]
  }
}

Note that in general you should not be using PHP code except as a last resort. It would be much better to use a custom action or condition instead. Both ways require writing PHP, but a custom action or condition is secure. In any case, neither is needed here.


Book page fields inherit content from parent I created a book with several book pages of a specific content type. I am trying to inherit the values of some fields from the top page of the book to the child pages so that i don't have to fill them manually on each page.

I tried the "Field default token" module with no luck. Actually it doesn't display the value of the token that i select.

Any ideas please?

The solution was fairly simple after all.
I created two content types and used a field with Entity Reference to pass the values from the first content type to the second one.


How to add up all items of a field collection field using Rules? I have a field collection with unlimited values.

Inside this field collection, there is a field called Price (field_price).

I would like to addup all prices that are inside the field collection to get the total value (which I will then set to the total value field that is inside the content type).

I know I can get all the prices like this:

But the tricky part is adding them up.

I tried adding Calculate a value to the loop but for data selectors I only get something like this:

And list-item:field-price is not available either.

All signs point that this is not the right approach.

Race ya to the answer.

  And list-item:field-price is not available either.

Turns out that I was in the right path all along, the reason this was not available to me when I tried to do calculate a value is because I had changed my price_field type to text-field. You can't do calculations on non numeric fields. After I changed it back to decimal, I was able to use list-item:field_price.

At first I thought your Rule needs to perform a Rules Component with 2 parameters (say 'current_total' and 'next_item') and simply calculate the sum of both, and return that sum to the Rule (using "provides" for that component parm). And then in your Rule update current_total with the provided sum, before the loop in your Rule ends.

However you don't need such Rules Component, only 1 rule will do. Have a look at this Rule (in Rules export format), which IMO is a prototype that does exactly what this question is about:

{ "rules_calculate_sum_of_prices_in_all_field_collection_items" : {
    "LABEL" : "Calculate sum of prices in all field collection items",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_details" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "\u003Cstrong\u003EDrupal calculator\u003C\/strong\u003E started ..." } },
      { "variable_add" : {
          "USING" : { "type" : "decimal", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "total_price" : "Price total" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-article-details" ] },
          "ITEM" : { "article_details_item" : "Article details item" },
          "DO" : [
            { "data_calc" : {
                "USING" : {
                  "input_1" : [ "total-price" ],
                  "op" : "+",
                  "input_2" : [ "article-details-item:field-price" ]
                },
                "PROVIDE" : { "result" : { "calculation_result" : "Calculation result" } }
              }
            },
            { "data_set" : { "data" : [ "total-price" ], "value" : [ "calculation-result" ] } },
            { "drupal_message" : { "message" : "After adding a price of \u003Cstrong\u003E[article-details-item:field-price]\u003C\/strong\u003E for field collection item with id \u003Cstrong\u003E[article-details-item:item-id]\u003C\/strong\u003E, subtotal is \u003Cstrong\u003E[calculation-result:value]\u003C\/strong\u003E." } }
          ]
        }
      },
      { "drupal_message" : { "message" : "The \u003Cstrong\u003ETotal price\u003C\/strong\u003E for all prices included as field collection items is \u003Cstrong\u003E[total-price:value]\u003C\/strong\u003E." } },
      { "drupal_message" : { "message" : "\u003Cstrong\u003EDrupal calculator\u003C\/strong\u003E ended ..." } }
    ]
  }
}

Some more details about this rule are below ...

Rules Event:

Content is viewed (of type Article), adapt the machine name of the content type article to whatever fits (or use any other Rules Event that fits).

Rules Condition:

Entity has field, whereas the entity is "node", and the machine name of my field collection field is field_article_details (adapt this machine name to whatever fits, but make sure you use the field collection field itself).

Rules Actions:

Here is where the magic will happen ... These are the Rules Actions involved:

Show a message on the site, with a message like so:

  Drupal calculator started ...

Add a variable, whereas it is a variable named total_price, decimal (2 digits), initial value 0.
Add a loop, to iterate over each item of my field collection field (with machine name field_article_details), and perform these Rules Actions for each iteration:

Calculate a value, which calculates the sum of total_price (defined in Rules Action 2 above) and article-details-item:field-price (this is the machine name of the field in the field collection that contains the prices, decimal with 2 digits), and stores the result (sum) in variable calculation_result.
Set a data value, which simply copies the value stored in variable calculation_result in my total_price (defined in Rules Action 2 above). Remark: not sure (not tested), but maybe this calculation_result variable can be replaced straight by total_price (in the previous action), so that you would not need this action.
Show a message on the site, with a message like so:

  After adding a price of 3.40 for field collection item with id 3, subtotal is 15.00.

Show a message on the site, with a message like so:

  The Total price for all prices included as field collection items is 26.23.

Show a message on the site, with a message like so:

  Drupal calculator ended ...

Obviously, this rule is rather a prototype. After you're convinced it works as it should, just remove all Rules Actions with Show a message on the site. So that only item 2 and 3 (without its last sub-bullet) is left as Rules Actions.

Showtime ...

Here is a sample of my test results, i.e. the Drupal messages that are shown:

Drupal calculator started ...
After adding a price of 2.45 for field collection item with id 1, subtotal is 2.45.
After adding a price of 9.15 for field collection item with id 2, subtotal is 11.60.
After adding a price of 3.40 for field collection item with id 3, subtotal is 15.00.
After adding a price of 1.23 for field collection item with id 4, subtotal is 16.23.
The Total price for all prices included as field collection items is 26.23.
Drupal calculator ended ...

More info

Processing Field collection items with Rules is fun, really! If you're not familiar with that, try to first digest the answer to "How to iterate over all field collection items in an eMail body using Rules?".


How do I add a super admin, either programmatically or directly through the database or another $new_user = array(
  'name' => 'Sg',
  'mail' => 'sg@email.com',
  'pass' => 'password123',
  'status' => 1,
  'field_custom_first_name' => array(LANGUAGE_NONE => array(array('value' =>'S'))), // This becomes $account->field_custom_first_name[LANGUAGE_NONE][0]['value']
  'field_custom_last_name' => array(LANGUAGE_NONE => array(array('value' => 'Doe'))),
  'access' => REQUEST_TIME,
  'roles' => array(), // No other roles than Authenticated
 //'roles' => array('10' => '10', '11' => '11'), // If you want to specify additional roles, the numbers are role_id's
);
user_save(NULL, $new_user);

I've seen this above code but where should I implement this code? I tried adding it and I got the error:

  user_save() is an undefined function.

I just need to be able to login to the system as a super-admin.

You have to create a super admin role(admin/people/permissions) and check all the boxes. And then you need to assign this role to the user.


DB connection works from the CLI, but fails from within Drupal I have set up a MySQL server on a machine with IP-address 192.0.2.9 (not the real address). The database user is named "drupal". Connecting to it using the CLI mysql command works just fine and the connection is accepted.

mysql -u drupal -p -h 192.0.2.9
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
...

However, when Drupal tries to connect to the same MySQL server from the same host, using the same credentials, I get this error:

PDOException: SQLSTATE[HY000] [2003] Can't connect to MySQL server on '192.0.2.9' (9)
in lock_may_be_available() (line 167 of /var/www/html/includes/lock.inc).

I have double checked that the correct database credentials and host are set in settings.php. I am at my wit's end, unable to figure out why this database connection works from the CLI, but not from within Drupal.

In case it matters: This is Drupal 7.41 and the OS on both machines is RHEL7.

Figured it out!

The client computer was running SELinux and was blocking outgoing connections over http. This pair of CLI command fixed it.

setsebool httpd_can_network_connect 1
setsebool -P httpd_can_network_connect 1


Can I use panels (page_manager?) to layout create/edit forms pages for arbitraty entity? I am new to panels and display suite both and trying to figure my way around those modules.

In "Display Suite" with "Display Suite Forms" you get an extensive list of all entities and bundles and can override any of the create/edit form layout.

In "Page Manager" I see only 'node add form', 'node edit form' and 'user edit form' context out of the box. Is there a way to generalize it and use "Panels" functionality with other entities on the site like Display Suite does it? I mean, without writing code.

What I want is to take existing entity, say 'commerce_customer_profile' and automatically have its 'X edit form' and 'X add form' contexts available in Panels. Or something equivalent.

I am new to panels and display suite both and trying to figure my way around those modules.

My preference is to use to Panels (or technically, Page manager) to control Context, that is, What to display Where.
Separately from that, you can use Display suite, or a recent favorite, Slate, for controlling rendering, or How things are displayed.
Allowing Page manager to render complete view modes instead of individual fields allows for much smarter caching most of the time, which can be a big performance gain.
If you're comfortable with code, Slate is significantly faster than Display Suite, for another large performance gain.

In "Display Suite" with "Display Suite Forms" you get an extensive list of all entities and bundles and can override any of the create/edit form layout.
In "Page Manager" I see only 'node add form', 'node edit form' and 'user edit form' context out of the box. Is there a way to generalize it and use "Panels" functionality with other entities on the site like Display Suite does it? I mean, without writing code.

'node add form', 'node edit form' and 'user edit form' are displayed as they are because the UI originates from D6, when there were no entities. The entire UI really needs a rewrite to be entity generic, but I don't know about anyone working on that.

What I want is to take existing entity, say 'commerce_customer_profile' and automatically have its 'X edit form' and 'X add form' contexts available in Panels. Or something equivalent.

Panels/Page manager has an entity generic context, but I think Display suite has deeper integration with entities.
You can bind any entity to a page as a context by creating a new Page, giving it a argument, for example %commerce_customer_profile and map it to the relevant underlying entity type.
To be fair though, I'm not sure this works for edit forms, I haven't had a reason to try that I can think off. If it doesn't, I can think of two things to do.

Implement a task handler. This is probably not trivial, but would allow full integration into Page manager. Could be contributed back to Ctools.
Use Page manager existing pages to take over the rendering of the existing edit forms. Using this module is likely a good option specifically for edit pages, as you should rarely be using Panels directly to tear up a form anyway; that can cause unintended data loss.

Because Display suite and Panels are often seen as some form of competitors (which I think is wrong), it's worth noticing that the author of PM Existing pages is also the author of Display suite.


How do you add help text to a form item? I would like to change the help text for an input field. My form ID is views-exposed-form-events-page-1. I have a text field that I want the helpful hint to appear below. The field ID is edit-field-event-date-value2, I think, based on the HTML.

From

<input class="form-control form-text" type="text" id="edit-field-event-date-value2-value-datepicker-popup-0" name="field_event_date_value2[value][date]" value="18/12/2019" size="20" maxlength="30" />
Date

 E.g., 18/12/2019

I thought that this would work, but I'm not seeing any help text appearing under the form field.

function mytheme_form_views_exposed_form_events_page_1_alter(&$form, &$form_state, $form_id) {
  $form['edit-field-event-date-value2']['#attributes']['description'] = 'DD/MM/YYYY';
}

What am I doing wrong?

The description doesn't live under #attributes, but under the element directly.

So you must do something like this to get it to work:

$form['field_event_date_value2']['#description'] = 'DD/MM/YYYY';

The HTML class is not the fieldname, but rather something like field_event_date_value2 in your case.

If that is not the correct fieldname, you can try to print_r(array_keys($form)) to see if you can see what the correct name is.


Views, Panels, Block not translating In a panel, I'm trying to add a view block and I'm trying to translate my views title  l but it's not displaying anything or translating. Below you can see my settings in my panels.

If I dont override the title, it's still blank. I dont see the English or the FR translations.

I thought there was already support for translatable pane titles in Panels with the i18n_panels submodule. However, looking at Issue #117934 which is currently marked fixed, there are still people providing patches. Though that issue title states it is for translatable Panel PAGE titles, the patch on comment #106 actually modifies code to make pane titles translatable.

Note that from an architectural perspective the approach in comment #106 is frowned upon because you are not supposed to pass dynamic text through t().  I would consider this a small permissible hack to get you across the finish line without wasting too much time.


Block region not outputting anything? I have this on my template:

  <?php print render($page['left']); ?>

And no matter how many blocks I add to the left sidebar region, nothing prints.

Any ideas?

Ah. Finally figured it out. The Left Sidebar is actually called sidebar_first. DSM'ed the $page variable.


Upload a file to a subfolder I'm working on a feature that will allow me to create series of nodes.  Each node will have a number of associated files.  I'd like to be able to upload the files to a directory that uses some fields from the parent node.  In other words, when the file is uploaded, a directory is used (or created if it doesn't exist yet) that uses the date the node was created and the title of the node.  I know I can specify a static directory to use when creating a file field, but I need create a subdirectory inside the parent directory. Is this possible?

If you look under your filefield settings you will see a field that called, “File directory” that is self-described as:

  Optional subdirectory within the upload destination where files will
  be stored. Do not include preceding or trailing slashes. This field
  supports tokens.

You can use tokens. Something like. [current-date:short]/[current-page:title]


apply a discount to product in Commerce I have a Drupal Commerce site and I'd like to apply a discount to the price where it is calculated. I have a table in the profile user with SKU | discount pairs and I'd like some way (maybe Rules?) to search the product on the table and apply the discount to the price.

Is there any way to do this in Drupal Commerce?

I use the Commerce Sale Price module with great success on my website. It is easy to configure. Just install and enable then you can set the discounts on the product pages.

Update: I think you could use Commerce Coupon to achieve your results. The coupons can be automatically applied based on a role. Sorry I did not understand your question fully before. Also, I have not used this module but the description appears to do what you want.


Form API to Database I have been reading Form API Quickstart Guide. I understand how it all works, but I don't understand how to save the data entered into the forms into my own database Drupal style.  Or am I supposed to use good old standard PHP to connect to the database to insert the data as required?

Is there a similar page to the form API quickstart page showing how to integrate a module with a database?

Connecting to the database and writing your own SQL, outside of the Drupal framework, while possible will put you in the dark ages. Drupal handles a lot of the heavy lifting and abstraction for you. If you are used to writing your own PHP to do DB queries it can be tempting to go with what you know. but  in the cases where you need to use custom queries use the Drupal DB API  like  Berdir suggested.

However often there are ways to use forms, without having to write your own database methods. Depending on what you want to do with the data there are several options.

Webform may be what you are after. Which will allow you to create custom forms with simple data management at the back end. Again fairly simple to implement but in this case you won't have the overhead of new nodes and the data is easily exportable.

In both of these cases you can use hook_form_alter to customize the form if you wish.


Context taxonomy term I have a context set up:

Condition > taxonomy term > vocabulary.

Reaction > some blocks displayed somewhere

This works ok for path like taxonomy/term/term_id but it doesn't work for something like taxonomy/term/term_id_1+term_id_2

Any ideas?
Thanks

This is a bit of code can help you I hope,

 <?php
   check_vocabulary = FALSE;
     $path = drupal_get_path_alias($_GET['q']);
     $pathnew = explode('/', $path);
     if ($pathnew[2]) {
        $vocabulary = explode('+', $pathnew[2]);
     }
    if ($vocabulary[0] == "your taxonomy") {
       check_vocabulary = TRUE;
    }
  return check_vocabulary;
?>

You should put it in the block under the tab Page specificy visibility setting, click on Show if the following PHP code returns TRUE (PHP-mode, experts only).

Now I'm not sure it's going to work with your setting and name but it could be a way for a solution.

 check_vocabulary = FALSE;

As we know, the system wants you to return TRUE to print the block so we set it false in the beginning so it's no going to print it and then remove it.

$path = drupal_get_path_alias($_GET['q']);
$pathnew = explode('/', $path);

In this part we take the path and we explode it so we get an array like this.

$pathnew[0]; Taxonomy
$pathnew[1]; Term
$pathnew[2]; Term_id_1+term_id_2

if ($pathnew[2]) {
    $vocabulary = explode('+', $pathnew[2]);
  }

We check first that $pathnew[2] exists and then we explode it to get all the vocabularies (if you want it separated). We split it by + so you will get

$vocabulary[0]; Term_id_1
$vocabulary[1]; term_id_2

Now we create the condition;

if ($vocabulary[0] == "your taxonomy") {
   check_vocabulary = TRUE;
}

You can compare what you want, that is just an example.

check_vocabulary = TRUE;

This is what the system wants to print the block.

return check_vocabulary;

This will return the variable FALSE or TRUE.

Let me know if it works.


Load form via ajax and submit by ajax not working I have loaded a form via ajax and submit by ajax not working. But if I load form directly by url ajax submission is working. Form is loaded by ajax is using jQuery.

$('#button').on('click', function () {
        $.ajax({
            url: "user_group/edit_ajax/",
            success: function (result) {
                $(".RblockMain").html(result);
            }
        });
});

mymodule.routing.yml

mymodule.user_group_edit_ajax:
  path: 'user_group/edit_ajax/'
  defaults:
    _controller: '\Drupal\mymodule\Controller\UserController::user_group_edit_ajax'
  requirements:
    _permission: 'access content'

UserController

public function user_group_edit_ajax() {
        $form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\UsergroupForm');

        $body_data = array(
            '#theme' => 'usergroup_edit_ajax',
            '#usergroup_form' => $form,
        );

        $message = \Drupal::service('renderer')->render($body_data);
        $response = new AjaxResponse($message);
        return $response;
    }

UsergroupForm.php

class UsergroupForm extends FormBase {

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

    $form['user_group_name'] = array(
          '#type' => 'textfield',
          '#title' => '',
          '#required' => TRUE,
          '#attributes' => array('placeholder' => t('Group Name'),),
          '#theme_wrappers' => array(),
        );

    $form['go'] = [
      '#type' => 'button',
      '#value' => $this->t('Submit'),
      '#attributes' => array('class' => array('btn btn-primary'),),
      '#ajax' => [
        'callback' => array($this, 'submitForm'),
        'event' => 'click',
        'progress' => ['type' => 'throbber', 'message' => NULL],
      ],
    ];
    }

public function submitForm(array &$form, FormStateInterface $form_state) {
 $title = $form_state->getValue('user_group_name');
$data = array(
        'type' => 'admin_user_group',
        'title' => $title,
        'uid' => 1,
        'status' => TRUE,
      );
      $usergroup = \Drupal::entityManager()->getStorage('node')->create($data);
$usergroup->save();
$response = new AjaxResponse();
    $response->addCommand(new AlertCommand('Submitted successfully'));

    return $response;
}
    }

I had the exact same issue:

When the form was on its own page, ajax submit works.

When the form was loaded through ajax, ajax submit didn't work, submit was redirecting the form to its own page.

After unsuccessfully restarting from scratch twice, I tried to implement this ajax modal example: https://www.mediacurrent.com/blog/loading-and-rendering-modal-forms-drupal-8/

Success one.

Then removing the openModalCommand to simply display the form on the page.

Success two.

I compared both my unsuccessful attempts and the successful one.
There was one difference, in the success one, in the controller the form was built but not rendered.

// Controller to load the form through ajax
public function ajaxSupportTicket() {
    $form = \Drupal::formBuilder()->getForm('Drupal\itportal_support\Form\SupportTicketForm');
    $ajax_response = new \Drupal\Core\Ajax\AjaxResponse();

    // Append the form in the page.
    // The form is sent as is, not rendered
    $ajax_response->addCommand(new \Drupal\Core\Ajax\AppendCommand('#selector', $form));

    return $ajax_response;
}

Now that this works, the whole ajax api of D8 seems very powerful.

Also, try to get rid of your custom javascript to load the form. It can be done using render array. Place a link with use-ajax class.

$output['open_form'] = [
  '#type' => 'link',
  '#title' => $this->t('Open Form'),
  '#url' => Url::fromRoute('mymodule.ajax_form_controller'),
  '#attributes' => [
    'class' => [
      'button',
      'use-ajax',
    ],
  ],
];

// Attach the library for pop-up dialogs/modals.
// drupal.dialog.ajax might be overkill, but I didn't took time to improve
// comments about it are welcome
$output['#attached']['library'][] = 'core/drupal.dialog.ajax';

Hopefully, it can help.


How to display the profile page in Modal window By using ctools, i am able to display a form in modal window.
Now i wish to display a page(the profile page) in modal window.

Below is the sample code (call by menu page callback) to display a html content in modal window, but how to display a page (user/1/profile) , i know i almost there..

any ideas?

function mymodule_profile_modal(  $user,$js)
{
  $output = t('
Lorem ipsum dolor sit amet...
');
  $title = t('Modal example');
  if ($js) {
     ctools_include('ajax');
     ctools_include('modal');
     ctools_modal_render($title, $output);
     // above command will exit().
   }

 }

This tutorial might help you:
http://drupion.com/blog/10-steps-creating-ctools-modal-window-drupal-7


Best method to clean up database table orphaned data in Drupal 7? Currently my files and images table has over 100k entries, but I know for a fact that alot of them are orphaned and the files do not exist anymore. What is a best method to cross-reference this data to see if the file exist so i can delete them?

This is a script I use on my own Drupal sites, you can see if it works for yours, it deletes files and records in the file_managed table that have no references in the Drupal file_usage table, or things that are no longer being used by the Drupal installation.

$result = db_query('SELECT fm.fid, fm.uri FROM {file_managed} fm LEFT JOIN {file_usage} fu ON fm.fid = fu.fid WHERE fu.fid IS NULL ORDER BY fm.fid');
$num_files_deleted = 0;
$num_records_deleted = 0;
$time_before_start = time();

foreach ($result as $record) {
    $file = file_load($record -> fid);

    if ($file != FALSE) {
        if (file_delete($file)) {
            print(drupal_realpath($record -> uri) . " has been successfully deleted.\n");
            $num_files_deleted++;
        }
    }

    db_delete('file_managed') -> condition('fid', $record -> fid) -> execute();
    $num_records_deleted++;
}

$time_after_finish = time();
$total_time = ($time_after_finish - $time_before_start);
$total_time_h = $total_time / 3600 % 24;
$total_time_m = $total_time / 60 % 60;
$total_time_s = $total_time % 60;

if ($num_records_deleted || $num_files_deleted >= 1) {
    print("\n\n");
    print($num_files_deleted . " files purged and " . $num_records_deleted . " in " . $total_time_h . ":" . $total_time_m . ":" . $total_time_s . ".\n");
}
else {
    print("Nothing to purge.\n");
}

You can try running that on a dev to see if that's also something you would want.


Deleted files for node are being included in view for services We are using the services module to provide a JSON feed for our internal portal to pick up our articles. The page view that provides all files for each node uses the File Usage: Content relationship. We just noticed that even files that have been deleted from the node are still being listed.

The query that views shows (when I take that same view and set as a block)

SELECT file_managed.uri AS file_managed_uri, file_managed.fid AS fid, file_managed.filemime AS file_managed_filemime, users_file_managed.mail AS users_file_managed_mail, 'file' AS field_data_field_caption_file_entity_type, 'file' AS field_data_field_file_image_alt_text_file_entity_type, 'file' AS field_data_field_file_image_title_text_file_entity_type
FROM
{file_managed} file_managed
LEFT JOIN {file_usage} file_usage ON file_managed.fid = file_usage.fid
INNER JOIN {node} node_file_usage ON file_usage.id = node_file_usage.nid AND file_usage.type = 'node'
LEFT JOIN {users} users_file_managed ON file_managed.uid = users_file_managed.uid
WHERE (( (node_file_usage.nid = '') ))

The nid is provided as a parameter.

How can I get it to not include files that were removed from the node?

You should use file_usage_delete to remove file usage records to nodes that files was having relations so you stop that problem for future deleting files on nodes.

And you still have to fix it for the existing nodes I suggest two ways

first : write a script to loop on file_usage records and check if the not currently used in the node (via node load and check fid exist) if so delete that record (if u have small number of rows in that table)

secod : Implement hook_views_pre_render  and do the same check.

the first is preferred however it may take long time but it will stop the problem reason