How can I print a custom message for unpublished nodes upon submission? Structure > Content type > ContentX > Edit > Unchecked published.

Structure > People > Permission > Anonymous users have access to create node for Content Type "ContentX".

An anonymous user goes to the page ../node/add/geo and fill up the form and be able to save the unpublished node. However, the user goes not get any message stating that the node is saved. I like to display a message to the user that user is saved and it is pending approval.

Based on my research, I need Rules module.

Enabled the Rules module for D8.

In Rules module, I like to configure it to display a message to the user when the unpublished node is saved.

Here I am not sure what to enter:

How would I configure the settings in Rules module to display a message when a node from a specific content type is saved but not published?

First, you should be using the current -dev version of Rules - that will make it much easier to do what you want.

Second, for the "Node is of type" condition, switch to the data selector for the first entry then select "node" from the data selector. This is the data object "node" that was created. For the content type, enter the machine id of the content type using the direct input mode (the default).


How to use smarty in Drupal 7 I have some prior experience in PHP programming but I had used Smarty as my template engine, and found it easy to use. I read that Drupal is making use of PHPTemplate as template engine. So, I just wanted to know how to implement Smarty template engine in Drupal?

While there is a Smarty module, it has no release for Drupal 7 and I doubt there will be one.

For Drupal 4 and 5, there were various efforts made to use different template engines.  However, nearly all contributed themes for Drupal 6 and 7 are done in PHPTemplate and almost all documentation and available support are for PHPTemplate.

Even if you're already familiar with Smarty, if you're going to use Drupal seriously for more than one project I would highly recommend learning PHPTemplate.  At this point, you would have to do work to integrate Smarty into Drupal 7 on your own, which would almost certainly be harder than just learning PHPTemplate.  Going with Smarty will also limit your support options.


IMCE stops uploading image in the middle of uploading I have a very strange case. I am using IMCE 6.x-2.2. and when my editors try to upload a new image, it stops uploading in the middle of the process and gives message: "A file with the specified name already exists.".
now when i check on the server, i found that it has uploaded part of the image only (image cropped).
this happens always on google chrome and sometimes on Firefox!!
any idea is highly appreciated

I cannot find the string "A file with the specified name already exists" anywhere in the source of IMCE 6.x-2.2.

Looks like the same issue was noted here on Drupal.org and was not part of IMCE

I would recommend updating to the newest version of IMCE in the 6 series to see if this fixes the issue. (Currently 6.x-2.3)


How can I make my ubercart catalog content available to users? I can't make my ubercart catalog content available to logged in users.

They can see the catalog page title but not the products.

This is what a logged in User can see:

This is my catalog views settings:

What I tried: I changed the rights for users already as shown below. Nothing happens.

What else am I missing?

Since you mention that authenticated users can't access your Product nodes, it's most likely that your nodes aren't published, or that there is a module interfering with the access check.

First, check if your nodes are actually published, on the Create or Edit form:

Second, go to /admin/people/permissions and check if anonymous users have the View published content permission.

Third, are you using any modules like Node Access that might alter the access permissions?


How can I execute a custom code on node edit/add page during hook_page_build? I'm seeking to show an extra form on node edit/add page. My function is this:

function mymodule_page_build(&$page) {
  $node = menu_get_object();
  if($node && $node->type == "object") {
    $page['page_bottom'][] = drupal_get_form('mymodule_form');

How can I check that current page is node edit/add page with a specific type like object?

The request_path() function can lookup the current path to determine what page is being rendered.

  if (request_path() == 'node/add/object') {
    // @TODO: Add code
  }
  else if (preg_match('/node\/\d+\/edit/', request_path())) {
    $node = menu_get_object();
    if ($node->type == 'object') {
      // @TODO: Add code for editing node
    }
  }


What format should date (ISO date) be when using Migrate Module? I have a large amount of date rows that I'm migrating over from a legacy application to Drupal 7. My destination field is Date (ISO Format) with year, month and day selected. What format should this be in when I'm migrating it across?

I can see that it's stored as 2010-01-01T00:00:00 in the database so I'm using prepareRow() to manipulate the data like:

<?php
public function prepareRow($row) {
  // DOB not migrated correctly - old = serialised array
  //    watchdog('temp', print_r($row, TRUE));
  if ($row->profile_dob) {
    $dobarray = unserialize($row->profile_dob);
    watchdog('temp', print_r($dobarray, true));
    $row->profile_dob = date('Y-m-d\T00:00:00', mktime(0, 0, 0, $dobarray['month'], $dobarray['day'], $dobarray['year']));
    watchdog('temp', print_r($row->profile_dob, true));
  }
}
?>

This returns the expected format for the date however the data is not populated in the database. I've tried using 'c' as the date format as well with no luck.

For date migration, you should use Migrate Extras module. Then you will be able to remove your code from prepareRow(), and just map the date field.

Migrate Extras will take care of reading you date and parse it.

In my migration I just had to set the timezone when I was importing birth dates.

Here's my mapping, as an example:

$this->addFieldMapping('field_birth_date', 'birthdate')->arguments(MigrateDateFieldHandler::arguments('Europe/Rome', 'Europe/Rome'));


Hiding Superfish Dropdown on Specific Menu Item I am working on a Drupal site that has a series of about 2 dozen articles. I have a page called "News" which lists the title/teaser for each article. I would like the menu item "News" to be active as the parent of each article node, but I would like to disable the dropdown menu (No need to have dozens of articles in a dropdown). I am using Superfish and have the dropdown enabled for all other menu items. Is there any way to disable it for a single menu item? Perhaps I need a different menu module?

Any help would be greatly appreciated. Many thanks!

susanhouser

EDIT

Here is a screenshot to help illustrate:

http://screencast.com/t/3eyDuK0w

EDIT02

I ended up coming across a solution that fit my need (See answer below). Instead of setting News as the parent menu item for each article (I was doing this to generate the class "active-trail"), I used the plugin described in my answer. Thanks for all of the help!

I ended up solving my problem by setting the url pattern for Articles to "news/[node:title]". I then used Menu Trails to highlight the News menu item based on the url path.

Now the "News" link will automatically be highlighted when viewing individual articles. Hopefully that helps someone else!


Commerce: how can I execute javascript after a product has been added to the cart? I want to run Javscript once a product has been added to cart (with the script including product info).

The only thing I have tried is hook_commerce_cart_product_add() with drupal_add_js() but this doesn't seem to work. Ideally I would like it work like drupal_set_message(), so the script displays on the next page view.

I also need to get this working with removing products from the cart.

EDIT: Well I've discovered that doing the following actually works, but seems dodgy as hell, and would like to find a better way:

drupal_set_message("<script>alert('TEST');</script>");

Any ideas would be welcomed!

You should better use Rules here and the related events. The hook you mention (hook_commerce_cart_product_add) is a rules event hook.

Commerce Cart: After adding/removing a product to the cart

Then on the action add with php the js (drupal_add_js()) but if you simply want to show a message there is an action to do this easily.

System: Show a message on the site


How to render $site_name without html tag? The $site_name variable get the name of the site wrapped in <a> tag but I want print only the value without html?

Is possible?

Thank you in advance.

  EDIT

  I'm using the strip_tags() function of php <?php print strip_tags($site_name); ?> but I don't know if is the best solution to solve the issue.

In a preprocess function you can get the title like this:

variable_get("site_name");


querying content type via drupal database API Using Drupal 7 I have created a content type called 'fauna'. I simply want to filter by an attribute (eg: 'area') using Drupal database API.

As far as I have seen around, most of people follow queries like...

$query = db_select('my_table_name')

applying then some filters.

But I have no table at all regarding my content type where I could apply these filters, i just have a bunch of tables field_data_field_fauna_name, field_data_field_fauna_area ... (these are the fields defined for my Content type).

Instead of querying directly against a table you can use Entity field query.

I'll assume the machine name of your content type is called fauna and that there is a field called field_fauna_area. Now lets find all nodes where the field field_fauna_area is "Europe".

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'fauna')
  ->fieldCondition('field_fauna_area', 'value', 'Europe', '=')
$result = $query->execute();
if (isset($result['node'])) {
  $fauna_nids = array_keys($result['node']);
  $fauna_items = entity_load('node', $fauna_nids);
}

In $fauna_nids you will find all node ids and in $fauna_items all the nodes will be loaded.


Import fields and field types I am developing a Management Information System in Drupal, holding thousands of suppliers in different certification schemes.
 Due to the nature of these certification schemes, and because of working with third parties, I need to import comprehensive surveys in CSV from other systems. I normally do that via feeds which works fine.

The issue now is how to deal with the big variety of D7 fields. In the present situation I need to key in all these fields, and map them to the import fields in the feeds. Lots of work with about 10 surveys carrying approx. 100 questions each.

Survey questions (= fields) and related Field types are however available in CSV.
 Would there be a way of importing Fields and Fields types from such CSV into new or existing content types, similar to https://www.drupal.org/project/webform_auto_field ?

Posted this question before under Entityform, only realizing later that the question would be more relevant under core.

I would use the Migrate module with the CSV as a data source.


How to add profile2 field data to a programatically created user I create a user from a form (that part works fine) but no profile2 information seems to be created....

profile2_load_by_user returns an empty array which results in the below error.  Do I need to some other step to first associate an "ae_sa" profile with the newly created user?

  Recoverable fatal error: Argument 1 passed to profile2_save() must be an instance of Profile, instance of stdClass given, called in D:\FULLREPO\trunk\sites\all\modules\sps_users\sps_users.module on line 115 and defined in profile2_save() (line 291 of D:\FULLREPO\trunk\sites\all\modules\profile2\profile2.module).

...
$account = user_save(null, $new_user);
$obj_user = user_load($account->uid) ;
$profile2 = profile2_load_by_user($obj_user) ;
$profile2["ae_sa"]->field_full_name[LANGUAGE_NONE][0]["value"] = $fullname;
$profile2["ae_sa"]->field_title_role[LANGUAGE_NONE][0]["value"] = $titlerole;
$profile2["ae_sa"]->field_company[LANGUAGE_NONE][0]["value"] = $ucompany;
$profile2["ae_sa"]->field_bio[LANGUAGE_NONE][0]["value"] = $bio;
profile2_save($profile2["ae_sa"]) ;

You need to create the new user's profile:

$profile = profile2_load_by_user($user->uid, 'ae_sa');
if(empty($profile)) {
  $profile = profile2_create(array(
    'type' => 'ae_sa',
    'uid' => $user->uid,
  ));
}

// Fill fields
$profile->field_full_name[LANGUAGE_NONE][0]["value"] = $fullname;
$profile->field_title_role[LANGUAGE_NONE][0]["value"] = $titlerole;
$profile->field_company[LANGUAGE_NONE][0]["value"] = $ucompany;
$profile->field_bio[LANGUAGE_NONE][0]["value"] = $bio;

// Save the newly created OR updated profile
profile2_save($profile);


How do I add grouping, programmatically? I've added a custom field to a view and want to display results as a grid grouped by this field. How do I set that "Grouping field Nr.1" option in my code? I tried the hook_views_pre_build() using the $view->addHandler but m not able to make it work. I guess the issue lies in the $option array and the $type parameter for addHandler method. Here is my code.

function utility_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'frontpage' && $display_id == 'page_1') {
    $options = array(
      'style' => array(
        'options' => array(
          'grouping' => array(
            'field_category',
          ),
        ),
      ),
    );
    $view->addHandler("page_1", "grouping", "node__field_category", "field_category", $options);
  }
}

Update
When I use $view->addHandler("page_1", "field", "node__field_category", "field_category", $options); I get the a catgeory field added to each of the view items.

Can anyone help me on this?

Finally found a solution. The grouping is not an Eventhandler in Drupal 8 but a Plugin (Style Plugin) specifically. Here is the code

function utility_views_pre_build(ViewExecutable $view) {
  $view->style_plugin->options['grouping'][0] = array('field' => 'field_category');
}


Hook_mail, drupal_mail and MIME mail I've successfully managed to send email by using drupal_mail and hook_mail, but the next step is to send attachment within the email.
I've read that this is not possible without adding extra modules, like MIME and Mail System.

OK, here's my code that sends email without attachments:

<?php
//The form page callback
function mymodule_news_page($form, &$form_state) {
    $form['title'] = array(
        '#type' => 'markup',
        '#markup' => '
Add news
',
    );
    $form['upload'] = array(
        '#type' => 'managed_file',
        '#title' => t('Upload image'),

    );
    $form['description'] = array(
        '#type' => 'textarea',
        '#title' => t('Description'),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#submit' => array('mymodule_news_submit'),
    );

    return $form;
}

function mymodule_news_submit($form, &$form_state) {
    $upload = $form_state['values']['upload'];
    $description = $form_state['values']['description'];

    $params = array('upload' => $upload, 'description' => $description );
    drupal_mail('mymodule', 'mymodule_news_mail', 'myemail', language_default(), $params);
    drupal_set_message(t('Message sent!'));
    //dpm($form_state);
}

/*
** Implements hook_mail().
*/
function mymodule_mail($key, &$message, $params) {
    switch($key) {
        case 'mymodule_news_mail':
            $message['subject'] = t('Hello');
            $message['body'][] = t('This is a test for adding news');
            $message['body'][] = t('Image upload: @upload', array('@upload' => $params['upload']));
            $message['body'][] = t('Description: @description', array('@description' => $params['description']));
        break;
    }
}

As you can see I have a form that has three fields: upload, description and submit button.
I'm trying to upload a image, but on submitting I receive an email with filled description and the uploaded image is not in the email, but it shows some numbers like 110...

Now I've enabled the MIME and Mail System module, and from their README module I can see this line: "'attachments':
      Array of arrays with the path or content, name and MIME type of the file (optional)."

I guess this is for uploading files, but there's no other documentation, so it's not clear how can I use MIME mail with hook_mail and drupal_mail().

What do I have to add in my code, so the uploaded file will be sent into the email?

No, the part in the documentation is not referring to file uploads, but indeed to mail sending. The expected array structure can look like this:

'attachments' => array(
  array(
    'filename' => 'text.csv',
    'filepath' => $filepath,
    'filemime' => 'application/csv',
  ),
),

or

'attachments' => array(
  array(
    'filename' => 'text.csv',
    'filecontent' => 'test content',
    'filemime' => 'application/csv',
  ),
),

Also have a look at this for another example: https://drupal.org/comment/5617230#comment-5617230

Edit: The attributes that you can use

filename: This is the name of the file as it will appear for the mails recipient. So you can freely choose this name.
filepath: If you want to attach a file that exists on your server, then this is the attribute that you want to use. Specifiy the full path to the file (e.g. image).
filecontent: If the attachement doesn't exist on your server but you want to send some content as an attachment, then you can use this attribute to pass on the content.
filemime: Here you can specifiy the mimetype of your attachment. This information gives the users mail application some basic information what to do with the attachment. An attachment of type application/pdf will probably open in the local pdf application, if the mimetype is image/jpeg it will probably open in an image viewer application.

filepath and filecontent are somewhat mutual exclusive. I'm not sure what will be the result, when you specify both.


Associate an image with each checkbox I'd like to have a graphics-oriented Webform, wherein the user will select from check boxes that have a specific image associated with each. For instance, I might have a row of checkboxes with a color swatch above each one, like this:

[red jpg color swatch] [blue jpg color swatch] [green jpg color swatch]
[checkbox].................[checkbox]..................[checkbox]

How can I accomplish that using the Webform module?

Thanks!

I used this CSS technique to make checkboxes larger and add background images unique to each checkbox. Sample LESS Code:

#edit-field-vegetables {

  input[type='checkbox'] {
    -webkit-appearance:none;
    width:70px;
    height:70px;
    background: url('../img/vegetables_icons_long.png') no-repeat;
  }
  input[type='checkbox']:checked {
    opacity: 0.5;
  }

  .form-type-checkbox{
    display: block;
    width:110px; height:110px;
    position: relative;
    float:left;
    input.form-checkbox{
      float:right;
      position: absolute;
      top:40px;
    }
  }

  .form-item-field-vegetables-und-orange input {
    background-position: 0 -753px;
  }
  .form-item-field-vegetables-und-banana input{
    background-position: 0 -1415px;
  }
  .form-item-field-vegetables-und-apple input{
    background-position: 0 -80px;
  }
}

This works on chrome. Look at the discussion linked above to see how to make it cross-browser.


How I can force enable clean url d7 Today i have transferred my d7 site to a new ubuntu vps, then in the Apache config files i made this change: AllowOverride None to AllowOverride All and now d7 site is working under clean url.

While transferring the website i have disabled the clean url option from the admin/config/search/clean-urls, but here is the difficulty. Now clean url works but in order to enable clean url when i click on the "Run the clean URL test" button then it shows "The clean URL test failed." though it is working :/

I have cleared all the cache data with no luck.

Now what are alternative ways to enable clean url manually in d7?

Clean URL state is managed through the Drupal variable clean_url.

clean url disabled: clean_url is 0
clean url enabled: clean_url is 1

You can force this value by:

Using drush

drush vset clean_url 1

Using a direct SQL query

UPDATE variable SET value=1 WHERE name='clean_url';

Force a value in settings.php

$conf['clean_url'] = 1;


Views Data Export Not working for current page I am using View Data Export to export users in csv.
I am using a page view. Fields, User Name, Email. Same fields in Data Export display type and filters.

In Data Export display, using Parent Sort Checked.

Here are the page and Data Export Display using same settings.

Data Export Display.

On Page Display I am showing 5 users, with full pager. On Data Export Display I am using 5 as well.

When I change page, goto next page on /export-user, CSV Icon cant export users other than first 5 no matter on which page I am.

So the csv Icon shows the same link on each page.

Any idea if I am missing something.

It seems issues with the module itself. You can just use view's template file or hook_views_pre_render() rather than attachment.

Append a link after views content or in footer called Export CSV.

Your code will be like this :

print l('Export CSV', 'userexport.csv', array('query' => array('page' => $_GET['page']));


Custom Condition on Query I'm trying to add a custom condition in a query:

 $today = new DrupalDateTime();
 $today = $today->format("m-d");
 $ids = Drupal::entityQuery('user')
  ->condition('status', 1)
  ->condition("date_format('field_birthday','%m - %d')", $today, '=')
  ->execute();

Error:

  PHP message: Uncaught PHP Exception
  Drupal\Core\Entity\Query\QueryException:
  "'date_format('field_birthday','%m-%d')

Version Drupal 8.8.4

What is the best way to solve this?

You can try use hook_query_TAG_alter

...
->addTag('my_module_birtday')

/**
 * Implements hook_query_TAG_alter().
 */
function my_module_query_my_module_birtday_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  $today = new DrupalDateTime();
  $today = $today->format("m-d");
  $query->addJoin('LEFT', 'user__field_birthday', 'field_birthday', 'field_birthday.entity_id = base_table.uid');
  $expression = "DATE_FORMAT(field_birthday.field_birthday_value,'%m-%d')";
  $args = [
    ':birthday'=>$today
  ];
  $query->where($expression . '=:birthday', $args);

}


How to add a custom marker icon on gmap using the gmap module? I want to add a custom marker to the list of markers on the gmap module
I tried the following link which is as described below :http://mydrupaltricks.be/article/drupal-7-custom-gmap-markers  but it did not worked

<?php
$markerdir = variable_get('gmap_markerfiles', drupal_get_path('module', 'gmap') . '/markers');
?>

By setting the "gmap_markerfiles" variable, we can change the location of our new markers folder. We have to set this variable only once so we put the code in our "my_module.install" file.

<?php
/**
* Implements hook_install().
*/
function my_module_install() {
  variable_set("gmap_markerfiles", drupal_get_path("module", "my_module_name") . "/markers");
}
?>
Now we can create the new "markers" folder in our new module. Gmap expects a .ini file to describe all your markers. We add the file "markers/my_module.ini".
; Defaults
[defaults]
; Note: An empty shadow property will break IE.
; Leave it commented out if you aren't supplying an image.
; shadow = ""
anchorX = 15
anchorY = 17
infoX = 17
infoY = 6

; Marker sets

[drupal]
name = "drupal"
sequence = "marker-green.png"

[salepoint]
name = "salepoint"
sequence = "marker-green.png"

[headquarter]
name = "headquarter"
sequence = "marker-green.png"

[shop]
name = "shop"
sequence = "marker-yellow.png"

You do not really need to write your own module (unless it does something out of the box) in order to use custom markers.

Here is an guide how you can do that (I assume we use gmap module and views module to display google map.

Upload you custom markers to Drupal website, f.x. to your theme folder (i.e. /sites/all/themes/yourtheme/images/markers or another location that suit you more.
In that folder you need to create an INI file and declare your custom markers (give them name etc). See example with 1 custom marker below.

Go to gmap settings /admin/config/services/gmap and specify folder where you saved your marker image and ini file (see image below).

Now make sure you saved everything and cleared cache.
Go to your view and in the settings you must get your custom marker available (at the bottom).


Meta-Tag Module that can use existing fields On my node, I have several existing fields, such as field_introduction and field_book_tags. These fields were created by me and do not come with Drupal by default.

I would like to know if there are any modules, which will let me use these fields for the Meta Description and Key word Tags.

The fields I need use for the meta tags will vary between content type, so the Meta tags solution must allow local overrides.

Here are some of the modules I have looked at:

Meta Tag, Custom Meta - Allows use of default Drupal fields only

Meta Tag Quick - Allows default Drupal fields only. Doesn't give much flexibility for selecting fields.

Simple Meta - Doesn't support any existing fields.

Beanstag - This allows the use of existing fields (via tokens). But, in order to target content types, a "folder" name has to be used in the URL (e.g. mysite.com/news/my-news for "news" content types, mysite.com/info/my-story for page content types). Although the folder name can be anything, I prefer my urls to be "folder" free (e.g. mysite.com/my-news)

It looks like BeansTag will have to make-do, but I thought I would ask in case anyone has better suggestions.

It appears to me that the solution currently being worked on in issue 1838554 is going to be a valid alternative to consider ... At least in the long run (and after the issue status reaches status fixed).


View of date field showing time on all day events I have a Event content type with a body and date field from the Date module.

I have a view that shows the events as a block in ascending order, and everything looks cool when I view as an admin. All day events are displayed without a time.

  Event Foo
  12/06/2014 to 12/09/2014

However when I look at the block as an anonymous user all day events show up as starting and ending at 2:00

  Event Foo  12/06/2014 - 02:00 to 12/09/2014 - 02:00

How can I get rid of the time?

Edit:
How the Date field looks in the node edit form:

Fixed this issue by creating a custom date format and date type.
/admin/config/regional/date-time


Custom editable, translatable email templates I need to send many different emails to drupal users. How can i add custom editable & translatable email templates? Something like user emails?

I have tried "Mail Editor" module, but i don't know how to add custom emails. Perhaps this is not the right solution?

thanks in advance

Using Mail Editor you can add custom emails by going to admin/config/system/mail-edit

Did you try doing that?

Regarding translation at - /admin/config/regional/language/configure there is a 'Follow the user's language preference.' option.


Why is menu item for custom module not showing? I'm new to Drupal and about to write my first custom module ("configurator") with help of the drupal documentation.

I've implemented the menu hook:

function configurator_menu()
{
    $items = array();
    $items['configurator'] = array(
        'title' => 'Configurator',
        'page callback' => 'configurator_init',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
     );
     return $items;
}

function configurator_init()
{
    return "<p> Hello World </p>";
}

At "Administer > Site Building > Modules" the module is shown and activated. Cache has been cleared, but somehow the menu item for my "configurator" module is not showing up.

Why?

You've either forgotten to set the menu_name key for the menu you want to add the link to:

$items['configurator'] = array(
  'title' => 'Configurator',
  'page callback' => 'configurator_init',
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
  'menu_name' => 'primary-links',
);

Or you want to use the default ('navigation'), but you're using the wrong type. It should be

$items['configurator'] = array(
  'title' => 'Configurator',
  'page callback' => 'configurator_init',
  'access callback' => TRUE,
  'type' => MENU_NORMAL_ITEM,
);

MENU_CALLBACK is:

  Callbacks simply register a path so that the correct function is fired when the URL is accessed. They are not shown in the menu.

Emphasis mine.


How to add/remove a permission from a user role to a particular user without modifiying the user role? Let's say that I have a user role called ARTICLE_VIEW_EDIT which has permissions to view and edit own articles nodes. I have the following 2 cases.

I want to give extra permission, delete own articles permission to a user - user101 who has the user role ARTICLE_VIEW_EDIT and this modification must not affect the user role.
I would like to remove edit permission from a user - user102 who has the user role ARTICLE_VIEW_EDIT and this modification must not affect the user role.

After doing some research I have found out that I could use the Role class to create custom user roles but that will be saved as configuration not as a record in the user__roles tables hence I am not getting the output that I'm looking for.

You can't do that, at least with standard Drupal setup. Probably you can code a hack that allows it, but is not how Drupal is designed.
Besides this, you can use current role system to achieve what you want. You only need to add more roles. You want edit own articles, view own articles and delete own articles to be independent. You can define 3 roles, and assign to users as you need.
If your problem is you'd have lots of roles (because you want lot of different permissions to be independent) you may use Content Access along with ACL:

This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.
[...]
It tries to reuse existing functionality instead of reimplementing it. So one can install the ACL module and set per user access control settings per content node.

Alternatively, you can code your own access system implementing a combination of hook_entity_access, hook_node_access and hook_query_TAG_alter.
You can have a full explanation of how node access rights works on this documentation page: https://api.drupal.org/api/drupal/core%21modules%21node%21node.module/group/node_access/8.8.x

Next, all implementations of hook_node_access() will be called. Each implementation may explicitly allow, explicitly forbid, or ignore the access request. If at least one module says to forbid the request, it will be rejected. If no modules deny the request and at least one says to allow it, the request will be permitted.


Where is the Profile2 field data hiding? I created a couple of different profile types in Profile2. I then register new accounts through /admin/people/add user (my-profile-type). All of my custom fields show up, and I enter the data accordingly. However, when I go back to the user's profile to edit it, the data isn't there.

Am I missing something obvious? Another post here said there was a button in the admin that gives access to the profile2 fields - but I don't see anything like that?

Each profile type comes up as a second-level tab on the user edit page, like this (using admin theme):

'Parent Information' is a profile type, and the 'Account' link is for the normal edit page.

If those tabs are missing from your theme I'd have a look at page.tpl.php to make sure you're outputting the tabs correctly.


How to easily create and reference a node / entity during creation of another one? I have the task of attaching two entities to each other, and both may not exist yet. So what I'd like is to create the second entity along with the first one if it does not exist yet.

So in the case of having a task and attaching persons, assume I already have created a person. Then I would like to add him to the task by typing in his name.
But at the same time, when editing a task and the field does not find a name, I like to receive the option to create the person entity on demand.

Are there recommendations as of how to approach this?

The References dialog module might be an option (if you're using the references project).

  This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog. This allows for a workflow where the user can create all the references to a node at the same time as she is creating it, a process which sometimes get's a bit backwards, when a user for instance needs to create all the facts for an article.

It doesn't do exactly what you've described, but it's pretty close.


Passing a Taxonomy term via URL to add content form in Drupal 7 OK, I have a Drupal 7 site.  And the scenario is that, let's say I'm on a page of my site that happens to have a taxonomy term assigned to it - let's say it's term ABC.  Well in a block in the sidebar I have a link that sends the user to the ADD CONTENT form for a Forum Topic.  The Form Topic content type has a CCK field as well (same vocab).  I'm trying to automatically populate that field with the same term ABC as the page that they came from.

I was thinking this could be passed via URL as a GET parameter, but not sure if that would work and if so how to pull it off exactly.

You can use the module Prepopulate ; latest release is dev but I use it on a production site and it works like a charm.

If it doesn't work tell me, there are two other solutions : send an arg in the URL to the form (and then use Panels or the php template) and JavaScript (I can give you the code if you need it).


How to use minipanels in a menu I tried to install the module Menu Minipanels, without success. I tried both the 1.x and 2.x version but the minipanel don't show up in the menu. After half a day I gave up.

I do like the idea of a megamenu using minipanels, so this question is:
How to use minipanels in a menu, without the 'Menu Minipanels' module?

EDIT: I got Menu Minipanels working at last, but it has a major bug that anonymous users can't see the minipanels in the menu! Back to square one.

So again the same question..

I now used a workaround, instead of the 'menu minipanels' module, i am using 'Menu Attach block' which simply allows to insert minipanels too since they are available as blocks.


How to get Q & A of a webform submission? Main goal is to get user filled in form into a pdf. Got my pdf & sending it with email. But I cant figure out how to get Q & A from a submission. I have sid of submission. I tried

      $storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
  $webform_submission = $storage->loadByProperties([
    'entity_type' => 'webform',
    'entity_id' => 'questionnaire',
  ]);
  $submission_data = array();
  foreach ($webform_submission as $submission) {
    $submission_data[] = $submission->getData();
  }

Webform is not attached to node.

Thanks

Try below code:

module_load_include('inc','webform','includes/webform.submissions');
$sid = 10; //Replace this value with your dynamic sid value
$submission = webform_get_submissions(array('sid' => $sid));
$nid = $submission[$sid]->nid;

$web_submission = webform_get_submission($nid, $sid);
$node = node_load($nid);
$output = webform_submission_render($node, $web_submission, NULL, 'html');

print $output;


Send data with post to other drupal page not working I'm trying to send data from a html form to another drupal page.

The Form (in JavaScript):

var data = { // JS Object with data to send
            priceUnit: '131.97',
            priceTotal: '131.97',
            priceCount: '1',
            articleNumber: 'XYZ'
        };
        // Form creation
        var form = document.createElement("form");
        form.style.display = 'none';
        // link to drupal site
        form.action = "../configurator/process_order";
        form.method = "post";
        form.target = "_blank";

        // Create form Content from JS Object data
        for (var key in data)
        {
            var input = document.createElement("input");
            input.name = key;
            input.value = data[key];
            form.appendChild(input);
        }
        document.body.appendChild(form);
        form.submit();

On the other page, I am trying to access php $_POST but there is no output:

<div>
     <?php
         echo $_POST['priceUnit'];
     ?>
</div>

But, if I add var_dump($_POST); in my module: configurator.module:

function configurator_process_order()
{
    var_dump($_POST);

    $modulePath = drupal_get_path('module', 'configurator');

    $content = file_get_contents($modulePath . "/Trader/PHPWebPages/processOrder.php");
    return mb_convert_encoding($content, 'UTF-8', mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
}

I get the following output:

array (size=4)
  'priceUnit' => string '131.97' (length=6)
  'priceTotal' => string '131.97' (length=6)
  'priceCount' => string '1' (length=1)
  'articleNumber' => string 'XYZ' (length=3)

So the form has submitted it's data but I cannot access it on my drupal page.
What am I doing wrong?

Your code:

<div>
     <?php
         echo $_POST['priceUnit'];
     ?>
</div>

is probably in one of the tpl.php files. They are cached. You are not passing any data from any module to your template file, so Drupal cannot know it is not supposed to be cached. That's all.

Access post data in your module file, and pass it to your template properly, the "Drupal way" you can see in Examples, and you'll be good.

Also, I strongly suggest to remember that POST data is user-agent provided and you should never trust it. Especially not for things like price! There is a Drupal Form API to automate tests, but what you really should pass around is item's ID, and it's price should always come from your database, not from your user.

Price supplied by client is a recipe for a legal disaster.


Partial start date with end date output views I'm using views to output a list of nodes with dates. Some node dates have both a start and end date inserted.

If both a start and end date exists, i would like the date to be outputted only taking the day from the start date.

Current: 9 January 2018 - 10 January 2018

Desired: 9 - 10 January 2018

I've tried using a custom field and rewriting the results in views, but this doesn't work. I've also looked in the pre_render and preprocess functions and only see the start date.

Any ideas?

I have resolved this issue using the compact daterange module, and using one of the committed patches.

https://www.drupal.org/project/daterange_compact


Change Entity Value In hook_feeds_presave() I am trying to modify data coming from a feed before it saved to a node by using hook_feeds_presave().

I have code that looks like this:

my_module_feeds_presave(FeedsSource $source, $entity, $item) {
     $email =  $item['email address'];
    //Remove "NOT GIVEN" from the email column to stop errors
    if($email == "NOT GIVEN"){
        $entity->field_email['und'][0]['value'] = '';
    }
}

I would think that when the node is saved that value in the email filed would be blank. However, it is still saving the value of NOT GIVEN.

If anyone can please point me in the right direction with this I would appreciate it.

Thanks,

Josh

Can you mention your Drupal version?

For Drupal 7, your code looks good enough at a first glance.
If it's Drupal 8, all you need is $entity->field_email = ''.

If that doesn't work, leave a comment and I'll take a detailed look.


Debugging JavaScript tests Recently started working on some JavaScript tests by extending JavascriptTestBase in drupal 8.2 and the biggest problem currently is debugging.

Phantomjs is installed and i have no problem running JavaScript tests. Xdebug is installed too.

$this->getSession()->getScreenshot();

is not returning any output, maybe some additional configuration is needed?

file_put_contents('/Users/me/debug.html', $this->getSession()->getDriver()->getHtml('/html/body'))

is giving me a half broken page.

I would really appreciate if someone can share how they debug these tests and how they set it up, some useful links. The biggest help would be to be able to take screenshots but any info on this topic is welcome.

I think that you are looking for JavascriptTestBase::createScreenshot() https://api.drupal.org/api/drupal/core!tests!Drupal!FunctionalJavascriptTests!JavascriptTestBase.php/function/JavascriptTestBase%3A%3AcreateScreenshot/8.2.x

See the following snippet from a core test:

  /**
   * Tests creating screenshots.
   */
  public function testCreateScreenshot() {
    $this->drupalGet('<front>');
    $this->createScreenshot('public://screenshot.jpg');
    $this->assertFileExists('public://screenshot.jpg');
  }


How to create programmatically menu links with just created nodes during installation profile in aegir ?can't get nid! I am creating a set of nodes in an installation profile.  When I try to create menu links for them in the same PROFILE_NAME.install, the links don't get created.

I have also tried creating the menus links in a separate module, and using hook_update_N() to enable them, but that also does not work.

When I uninstall the module and reactivate it, it creates correctly my menu's links correctly.

I tried to use hook_install_tasks() and put it in MYPROFILE_NAME.profile or MYPROFILE_NAME.install, but this also doesn't work.

How can I create menu links for nodes created as part of an installation profile?

My code for creating the nodes in MY_PROFILE_NAME.install is:

// creation of my nodes (same content for all)
   $nodi = array(
       // i have other 14 nodes
      'title' => array('Home'),
       // i have other 14 paths for the nodes
      'path' => array('home'),
   );
$titoli = array();
$titoli = $nodi['title'];
$percorsi = array();
$percorsi = $nodi['path'];
//CREAZIONI DEL CONTENUTO PROGRAMMATICAMENTE
  for($i = 0; $i< count($titoli); $i++){
$testo_body = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec feugiat velit eget metus placerat,varius eros facilisis. Aenean aliquam imperdiet nisl ut dapibus...';
           $node = new stdClass(); // nuovo oggetto nodo
           $lingua = 'it';
           $node->type = "page"; //
           $node->title = $titoli[$i];
           $node->language = $lingua;
           $node->path = array('alias' => $percorsi[$i]); // i think here is the problem !!!
           $node->uid = 1; // admin
           $node->status = 1;
           // Body field
           $body_field_info = field_info_field('body');
           if (field_is_translatable('node', $body_field_info)) {
              $body_lingua = field_valid_language($lingua);
           }else{
              $body_lingua = LANGUAGE_NONE;
           }
           $node->body[$body_lingua][0]['value'] = $testo_body;
           $node->body[$body_lingua][0]['summary'] = 'text...';
           $node->body[$body_lingua][0]['format'] = 'full_html';
           $node = node_submit($node); // Prepare node for a submit
           node_save($node); // After this call we'll get a nid

And my code for creating the menu links is:

    // Create a Home link in the main menu.
  $path = drupal_lookup_path('source', 'home');
  $item = array(
    'link_path' => $path,
    'router_path' => $path,
    'link_title' => st('Home'),
    'menu_name' => 'main-menu',
    'weight' => -50,
    'customized' => 1,
    'plid' => 0, // Parent menu item, 0 if menu item is on top level
  );
  menu_link_save($item);
  menu_rebuild();

Update 2

The menus are created in the menu_links table but with empty link_path so i can't get the nid created nodes.
I treid also to override the install_finished() and put my function for creating menus in .install or in .profile files, but it's the same.
Any ideas?

You can add a menu item using this

$item = array(
        'menu_name' => 'menu-name',
        'link_title' => 'Link title',
        'link_path' => 'node/'. $nid,
      );
menu_link_save($item);
//don't forget to clear menu cache after saving menu item
menu_cache_clear_all();

Hope this will help

Updated Answer
As I looked into Drupal 7 standard profile installation file, that is standard.install (Line no 413), you can see "Home" link creation there.

// Create a Home link in the main menu.
  $item = array(
    'link_title' => st('Home'),
    'link_path' => '<front>',
    'menu_name' => 'main-menu',
  );
  menu_link_save($item);

  // Update the menu router information.
  menu_rebuild();


How to update a computed field in a rule's "set data a value" action I have a custom field called field_balance in the user account form which is a computed field. It keeps the actual number of coins bought by the current user. That value is supposed to change (increase or decrease) if the user makes particular manipulations on my custom content type which is called Ads.

How do I increase the field's value? By setting up the field.

How do I decrease the value? I am using Rules module to make the field's value decrease. But it doesn't work well yet. This is what I have already tried:

The Event: After updating existing content of type Ads
The conditions: User has roles "ad editor"
The Action : Set a data value. But when I select the field called
"site:current-user:field-balance" and hit "Continue", The Data selector turns red and a notification appears.

Here is the illustration:

What is it about the computed field that does not continue the rule? Is there any other way to update a computed field with the Rules module?

I cannot answer your question directly, so I will propose a solution without computed fields for your specific situation. Since your computed field is just a sum of two other fields, it is perhaps easier to replace it with an ordinary integer field Balance and update its value with a simple Rule every time the entity in question changes. In order to allow users to see the field Balance, but deny them access to edit it, you can use the Field Permissions module:

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.


Multiple Rules under Rule Set I am trying to create a Rule set which has 4 Rules under it. Using this Rule set as an action in a Triggered Rule. I want that when any of the these 4 Rules is True, the action is triggered.

But looks like the Rules under Rule Set is assigning them AND condition. How can I set it to OR condition.

I have tried changing the logical operator to Or for each group. But that is not working.

Am I missing something, or this feature is not a part of Drupal 6?

Ok. I got my problem. I was using checkbox cck field. So the Rules were checking all values to be matched. To overcome this issue, I used Rules Bonus Pack module and in that used "Field value is one of several" condition.

Finally got it working as desired!


Blocks placed in content region appear in wrong positions Is there something I need to know about the way drupal handles blocks in the content region? I have a very bare bones omega subtheme with a single page promoted to front and two blocks in the content region positioned after the main content 'block' - but they show up before the main content.

I moved the blocks around to different orders and back and they suddenly appeared in the correct positions. Seems that they just needed some fiddling. Please comment if you have a similar experience, I'm interested.


How to filter views results based on entity reference field I use Drupal 7 and entityreference module.
I have a content type with a entity refenrece field to users called field_users_referenced.

So I created a view with views module and list nodes of thats content type.
I want to order this views result based on field_users_referenced.

when I add field_users_referenced field on filter fields, and set it for exposed filter , after type a field_users_referenced value on thats field, have no any result.

I do not want to filter field_users_referenced with select box, I want to type value on exposed filter field and order results.

please help me.

Advance View Settings -> Add Relationship -> Select Entity Reference Field

Then in filters -> add Filter-> Select field from the respective entity.

Thanks


Theming blocks in Panels Does anyone know of a module or some other way to allow users to customize blocks or panes (or even regions) in a panel on their profile page (i.e.: the authenticated user could change the color background of the block, or add a picture to the background, could change the color of the borders and font, etc?)

That means the same blocks could be themed differently by all users.

Ideally each block / pane would have a tab with some kind of a drop-down allowing the user to select options to add HTML and CSS on a per block basis.

The site uses Bartik (D7.)

Any feedback on this would be greatly appreciated. :)

Just some ideas:

I use the Fieldable Panels Panes a lot on smaller web page to add direct content to the Panel pane instead of having to create content for it first. FPP are entities. Maybe you can use for a user to add images (and text, files, etc.) to their profile page? Honestly, I've only used it on site building level.

I know about this module Classy Panel styles, but never used it. Maybe you can also set the permissions that users can use the pre-defined styles.

There is also a widget type module (as used in Atrium) where a user can move blocks (Panel panes) around. I don't have a link for that.


How to avoid clearing the cache after every CSS change? I use D7 and I'm tired of clearing the cache after every css change (I make lot's of changes to my online site, about ten's in a day)... Clearing the cache ten's of times a day consumes too much life time for me and I really had enough of it.. Yes - Even if it is made by the Admin Menu module.

Is there any way to temporarily disable the cache or something of the sort?

Notes:
Screenshot of my Performance settings attached.

Clicking ctrl+R never helps
Clicking ctrl+F5 never helps

On the admin/config/development/performance page under 'Bandwidth optimization' uncheck "Aggregate and compress CSS files.".

If you're looking for more control https://www.drupal.org/project/advagg/ is what you're looking for. Using the development setting in AdvAgg will detect the changes and push them out automatically.


hook_form_alter setting select list #options key allow attributes per option I have a select list that I am populating $form['field_my_field']['und']['#options'] in a hook_form_alter.

I was wondering what a good way to set a data attribute per each option would be. I've thought about adding some inline javascript to add it after it's rendered, but I want to do this with PHP and preferably within the hook_form_alter.

Is this possible?

Based on theme_select which is the one that constructs and styles the Drupal Form API's select type. It uses the form_select_options function do create the <option> tags.

So you would need to override theme_select and replace the form_select_options function with your own.

Basically, copy the functions and it's content, rename them and do your modifications.


Where to use setTrustedProxies() or how to set new trusted proxies I need to set a trusted proxy in my installation so that secure cookie flags are set correctly.

Currently as a temporary measure i am setting the following in index.php

$proxies = ['122.128.0.1'];
Request::setTrustedProxies($proxies);

However i would like to be able to set a new trusted proxy from a settings file or module that will persist through a core update without needed to patch.

Where is the best place to specify this?

Drupal doesn't want you to place custom code in index.php to prepare a request before it is handled by the Drupal kernel. So it was made possible for modules to implement a middleware through StackedHttpKernel.

In this case such a middleware already exists, which reads the reverse proxy addresses from settings.php and adds them as trusted proxies to the request:

Drupal\Core\StackMiddleware\ReverseProxyMiddleware::setSettingsOnRequest:

  $proxies = $settings->get('reverse_proxy_addresses', []);
  if (count($proxies) > 0) {
    $request::setTrustedProxies($proxies, Request::HEADER_X_FORWARDED_ALL | Request::HEADER_FORWARDED);

So you can simply enable this settings in settings.php:

$settings['reverse_proxy'] = TRUE;
$settings['reverse_proxy_addresses'] = ['a.b.c.d', ...];


Keep track of which user fully downloaded a file I'm looking for a solution to check which users fully downloaded a specific download/file.
I found several solutions to detect whether a download/file is completed.
F.e. https://stackoverflow.com/questions/1106377/detect-when-browser-receives-file-download
But this use case is quiet different. I need to retrieve a list of people who downloaded the file afterwards.

Thanks in advance.

If you have file_entity installed, you can use hook_file_transfer() with a custom function my_custom_registration($file, $user) that registers which user downloaded which file
The starting code for that is :

/**
 * Implements hook_file_transfer().
 *
 * @param type $uri
 */
function my_module_file_transfer($uri) {
  global $user;
  $files = file_load_multiple(array(), $conditions = array('uri' => $uri));
  if (!empty($files)) {
    $file = reset($files);
    my_custom_registration($file, $user);
  }
}

hope this helps


Secure Pages Domain Access for Drupal 7 I ran into a problem using Secure Pages with multiple subdomains. Secure Pages only seems to allow you to put one domain for SSL and not secure pages. I found the following module in Drupal 6, but I'm wondering if there is another project people know about to solve this problem in Drupal 7?

https://drupal.org/project/securepages_domain

You can actually just leave the base URL and Secure URL blank to not have it redirect to an inappropriate subdomain than you're on currently.

To restate my problem, I had multiple subdomains sharing one database where the Secure Pages module was implemented. If I put down a base and secure URL using one subdomain, I would get redirected to that instance from other subdomains not listed there when https was needed for that subdomain.

This is an undocumented solution as far as I'm aware, so I hope it helps someone else out.


how to see node revision user in a view In drupal 7, I have revisions turned on, and I want to make a view to display the last updated date and the user who last updated it.  The problem is I cannot get a field for "revision user" as an available field to see .    The only revision fields available are the updated date, and log message.

Please create view (content revisions view) like below images:

In view relationships please add  content revisions : user  for user information

Thanks!


What's the difference between these multi-site setups in Drupal 6? I am migrating several Drupal 6 sites to a new host. I recall the installer automatically set up my multi-site tables with just a few settings in the installer. I couldn't find these settings while I am making this migration and discovered description of multi-site configuration.

My original multi-site is of this type: Example one (this page explains a multi-site using $db_prefix property in a site's settings.php file).

During this file migration I found this type: Example two (this page explains manually crating a database table [database_name]_shared_tables).

As I said, my four sites were setup as with version one above. As I work to restore these sites from the mysql dump files, I'm wondering which process will be faster? My sites work like this,

+ default.domain (main drupal app)
|- sub1.domain (separate data)
|- sub2.domain (separate data)
|- sub3.domain (separate data)

Some of the information about multi-sites is outdated. This page suggests there are tables which can not be shared. Yet my settings.php file did not have a detailed list of shared tables, and instead had a simple prefix value, and leads me to believe the first example resolves what to share for you.

I once wanted to do multisites but it became so difficult to share data without sharing ALL of the data that I stopped. I wanted to share forum content, but not page content which is impossible. It is all nodes or on nodes.

The biggest problem with doing the $db_prefix method is everything is done in your settings.php file. I shared the variables table which shared every module setting. This method then included overriding all every variable you care about. For me if was a different  google analytics code. Since this is stored in the db and I was sharing the variables table, the analytics ID was shared.

The most important table to keep up-to-date is the sequences table (auto-number table for databases that do not auto number easily) that stores the next user id to be used. If you share users, you have to have that table in lock step with the rest. It is easily edited to change the users_uid value to be the next user id in the system.

So my answer will be another question. What do you want to be shared. Users? Roles? Taxonomy? Nodes? The more you share, the more tables have to be shared and the more overhead it is.

As a side note, the documentation is very outdated. I only recommend doing this on a dev and not production copy of your database and make sure you have a backup of a working settings.php and a full backup of the drupal database. This will help to roll back and keep your site running in the event something goes wrong.

In the settings.php I have the same $db_url as all of the sites. The exception is the below items.

$conf = array(
  'site_name' => 'My Site Name',
  'theme_default' => 'my-=sub-theme',
  'site_slogan' => 'My site slogan',
  'site_frontpage' => 'my_site_view',
  'smtp_fromname' => 'SMTP Settings From',
  'site_footer' => 'Site Footer',
  'googleanalytics_account' => 'UA-112233-1',
);

Any variable inside the variables table can be set in $conf. This helps my having a different theme on my sub domain site as well as a different frontpage view. I setup a taxonomy that puts the content into the view and then out to the frontpage. I took the example frontpage view included in views and cloned it and edited it to my needs. This was a quick and dirty solution to share the nodes but keep the frontpage content separate and track each site with its own google analytics. It works but I know there are shortcomings. The major one being that content can still be searched for on both sites that does not technically belong there.


How add Ckeditor on EntityType field I make a custom Entity content module, and for a field i want ckEditor.

Here my code for this field :

$fields['description'] = BaseFieldDefinition::create('string_long')
    ->setLabel(t('Description'))
    ->setRequired(true)
    ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'string_textarea',
        'weight' => -4,

    ))
    ->setDisplayOptions('form', array(
        'type' => 'string_textarea',
        'weight' => -4,
        'settings' => array(
            'placeholder' => 'Description de votre annonce',
        ),
    ))
    ->setDisplayConfigurable('view', TRUE)
    ->setDisplayConfigurable('form', TRUE);

  Type : string_textarea

How can i tell Drupal 8 to get the widget for textarea basic html mode ?

There are 4 different field types that contain a text

string
string_long
text
text_long

What long means should be obvious, the difference between string and text is that text has a format (like full_html or basic_html) while string is always plain text.

You are currently using string_long, it doesn't make sense to show a wyswiwyg editor for that, since it would always escape all HTML. Use text_long instead.


Show fields from diffrent content types in same view? Im using Drupal 7.x Merci, views, panels, chaos tools, rules, etc. I am working on a equipment checkout system, and I have a view that lists all the reservations made. In that view I would like to not only show the fields from the Content Type:Reservation, but also the picture from the Content Type:Customer.  I know that I need some kind of reference field so that I get the correct picture next to the correct reservation, so they have several fields in common, Customer Name and L#. I would prefer to use L# but i'm not sure what reference I need to use (entity reference, node reference, field reference) I already have the view built displaying the reservations. Any help would be great, there are lots of questions around about this but I haven't found one that touches on this.

Thanks in advance :)

Depending in the setup, the person who makes the reservation might also be referenced via the author field in views, but I don't know how your reservation system works.

Properties of other entities can be embedded in a view via the relations in the advanced section. There has to be a common field such as an entity reference linking the two content types together, but author, tags and several other properties can be used as well.

After adding such a relation, New fields will become available in the fields, filter and sorting sections.

UPDATE

I believe there is some misunderstanding about the modules. An entity reference (or any other reference in Drupal) uses the user id (uid) not a custom field #L. So when you add such a reference to a content type, you can only find users by username (or common name if realname module is installed). Since you said you have the customer name this should not be a problem as you select the users by name, but their uid is stored in the database.

Make sure there is only one relation on the content type that is created on the desk (registration). Adding an entity reference on the user (or both content types) makes no sense; a registration is made for one or more users, user's don't own one or more registrations.

Create a view listing fields of the main content type you want to display (registration). Then add a views relationship to the user object via the entity reference field. Finally you can add all fields of the user object to your list of fields.

The only filters you will need are filters for limiting the set of registrations (you could add contextual filters to list registrations per user), but I'd leave out all registrations to start with. You can always add them later.


Getting an element of a CCK field to use and modify in hook_form after_build I have a partially working solution for using hook_form after_build on a CCK field. The field has various elements (it's created with a custom module but I don't want to modify that so I've created a small overrides module to do some trivial form alter stuff.) I've been at this a good part of the day and finally had some luck adding some simple text to the field so I am know I'm getting close.

In the main module, the CCK field has various elements. Once such element is:

$element['week_night'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Week Night'),
    '#default_value' => isset( $element['#value']['week_night'] ) ? $element['#value']['week_night'] : NULL,
    '#attributes'    => array( 'class' => 'rate-widget-rate-field' )
  );

I am targeting the field itself in my overrides module as such:

<?php
function rates_override_form_alter(&$form, $form_state, $form_id) {
  //drupal_set_message($form_id);
  //dsm($form);
  if($form_id == 'ldisilink_property_node_form'){
    $form['#after_build'][] = '_rates_override_after_build';
  }
}

function _rates_override_after_build($form, &$form_state) {
  // This works so we know we are good to this point:
  $form['field_rates']['#prefix'] = 'do stuff';
  // Now we want to change the label on week_night but it's not working.
   $week_night = $element['week_night'];
   $form['field_rates'][$week_night]['#title'] = 'My new label title';
  return $form;
}

What I am trying to do is alter the label for the element week_night.  Using dsm($form) I've tried various combinations of:

   $week_night = $element['week_night'];
   $form['field_rates'][$week_night]['#title'] = 'My new label title';

... but it's not working yet, but I think I'm close.

You are on the right track. You want to set the #title attribute of the form element whose label you want to change, which can all be done at the hook_form_alter() time.

In order to change the label of the 'week_night' form element, try something like this:

function rates_override_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'ldisilink_property_node_form') {
    $form['field_rates']['week_night']['#title'] = t('My new label');
}

This is assuming the 'week_night' form element is nested within 'field_rates' fieldset. If that is not the case, use:

$form['week_night']['#title'] = t('My new label');

instead.


Displaying nodes and forms in a block for processing I am trying to build a module that enables users to use Drupal as a front end for a BMP engine. Users will be able to use Drupal content in their Processes. For example filling out forms or approving nodes for publication. Filling out a form or approving something will be the completion of a step.

My idea is to display the Drupal content (node, form) in a block and display the step description above it and a button underneath it stating: "Complete Step".

The BMP engine tells Drupal what to display in the block through a node_id or a form_id. Adding a button to a form seems quite easy (even though a way that will always removing/replace the button that calles hook_form_submit is welcome). The Problem is displaying this same button under a node.

After trying a lot of things I am down to this (and it does not work yet but it should not be that big a problem...)

//get the node object
$node_object = node_load ($step['DrupalID']);

//get our node submision form
$form = drupal_get_form('pm_form_form');

$output = drupal_render($form);
$output .= drupal_render(node_view ($node_object, true));

Yet it feels like a hack... can anyone suggest a better idea?

The Form Block module lets you easily create "block versions" of your add node forms. These block versions are still forms like any other in Drupal so you can use hook_form_alter to change the Submit button text to whatever you like and/or add any submit/validation handlers as required.


how to redirect page for anonymous users after number of times? if any anonymous users come to my site after number if times they are accessed but i want redirect to register page after 4 time viewed content in my site.

please tell me is there any modules available in drupal 7.

I don't think there are any contrib modules which can provide this functionality. This is not an ideal way but you can do it like this, I think:

Create a table (id, host_name, hash_code, visit_count)
Whenever you opens your site you will check for host_name, hash_code, and visit_count (if user is anonym)...

Example:

/**
 * 1 - I named the function as 'test' but this function must be called
 * at page load, that's why you need find where to call it. may be
 * TEMPLATE_preprocess_page() or HOOK_init()...
 * 2 - I can't say that here is everything is correct. Correct it if
 * something is wrong.. because I didn't test it...
 */
function test() {

  if(user_is_anonymous()) {
    $host_name = ip_address();
    $hash_code = genCode(35);
    $query = db_select('MY_tABLE', 'mt')
      ->fields('mt')
      ->condition('host_name', $host_name, '=')
      ->range(0,1)
      ->orderBy('id', 'DESC')
      ->execute()
      ->fetchAssoc();

    if(empty($query)/* This user is the first time came to your site */) {
      $record = array(
        'host_name' => $host_name,
        'hash_code' => $hash_code,
        'visit_count' => 1,
      );
      drupal_write_record('MY_TABLE', $record);
    }
    /* This means that the user is anonymous but not a new user */
    else {
      if(isset($_COOKIE['anonym_code']) && $_COOKIE['anonym_code'] == $query['hash_code']) {
        if($query['visit_count'] > 4) {
          drupal_goto('user/register');
        }
      }
      else {
        setrawcookie('anonym_code', rawurlencode($hash_code), 0, '/');
        $visit_count = $query['visit_count'];
        $new_record = array(
          'host_name' => $host_name,
          'hash_code' => $hash_code,
          'visit_count' => $visit_count + 1,
        );
        drupal_write_record('MY_TABLE', $new_record);
      }
    }
  }
}

// Helper function
function genCode($length) {
  $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
  $string = '';
  for ($i = 0; $i < $length; $i++) {
    $string .= $characters[mt_rand(0, strlen($characters) - 1)];
  }
  return $string;
}

I am sure that there are tons of bugs in that function;) I didn't test it... Also You need to implement hook_user_login() to delete a record from MY_TABLE right after the user registers and logs in.

P/S: Use this approach if you don't care about performance...


Condition on current moderation state I would like to show a message when content has changed moderation states from review to published. I set this up below but it does not work. Is there a rules debug log in Drupal 8?

Event:  When content is update.

Condition: Data Comparison.

node.moderation_state
Operator: ==
data value: published

Action: Send System message, with

The message type
drupal_get_message(‘status’);

But this doesn’t work. I get this error:

  error   php  InvalidArgumentException: Cannot set a list with a non-array value. in Drupal\Core\TypedData\Plugin\DataType\ItemList->setValue() (line 59 of /var/www/html/d815/core/lib/Drupal/Core/TypedD

Part 1 - Understanding the problem

I'm not sure if you won't run into other problems in trying to get this to work in D8 (as per the current status of the Rules module for D8), but IMO the first issue you need to resolve is that "...Cannot set a list with a non-array value ..." (as contained in your error message).

It seems to me that you should use something like what in D7 is called "List contains item" as your Rules Condition. For way more details on that, refer to the answer to the (D7 related) question about "Loop through all entities with rules".

Part 2 - More info that may help to get it to work

Your issue appears to be related to the (fixed) issue (= a task, not a bug ...), from Klausi, about "Support multiple contexts in the UI" which states:

  Currently we only use a simple textfield for contexts in conditions and actions. Conditions such as the UserHasRole condition have their Roles context defined as multiple, which means the user should specify more than one value in a text field. A default implementation could just display a textarea where one line is one item in the list.

The fix for this issue appears to be included in this pull request.

Disclaimer: I have not QA-reviewed this (yet) (but that's what I would go for to get it to work).


How to get taxonomy contextual filters working by name for users? I have users sorted by taxonomy. I created a page, added a field to a contextual filter and it works, but by ID only. I want user friendly paths, so I need it to work by name. All solutions I've seen was for nodes, where contextual filter is Taxonomy:. There is no Taxonomy: filters category for users, i need to use User: field_name and I can't get it to work.

You should just be able to add the Taxonomy field you associated with the user as a relationship, and then filter on that.


When to use drush_log() or drush_set_error()? I just trying to show an error message with drush and I see that you can achieve this with

drush_set_error('NON_EXISTENT', 'Message');

and with

drush_log('Message', 'error');

In both cases you will see the same error message, I read the functions documentation but I can't figure out are the differences between they?

In general, you should avoid using the status code 'error' when calling drush_log directly. Use drush_log to signal non-terminal events, usually with a status code of warning or notice.

If a function fails and cannot continue, the best thing to do is to exit with return drush_set_error(...);. This sets internal state, so that Drush knows that there was an unrecoverable error, and calls through to drush_log('Message', 'error');.


Edit specific menu items in template In my theme I'd like to have complete control over my menus. I'd like to apply specific classes and wrap the menu however I like. I was thinking I could do this within a template. I see that you can print the menu with this:

<?php
$menu = menu_navigation_links('menu-your-custom-menu-name');
print theme('links__menu_your_custom_menu_name', array('links' => $menu));
?>

But I'm not sure how to edit the individual items within the menu.

Menu attributes module is for what you want. Some details from its project page:

  This simple module allows you to specify some additional attributes
  for menu items such as id, name, class, style, and rel.


How can I upload 1000s of nodes per hour to a live drupal 7 site and avoid deadlocks? Not too long ago I wrote about deadlock here: PDOException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock;

Despite everything my development team tries to do, we still get errors like this:

  PDOException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found   when trying to get lock; try restarting transaction: INSERT INTO     {location_instance} (nid, vid, uid, genid, lid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] => 1059 [:db_insert_placeholder_1] => 1059 [:db_insert_placeholder_2] => 0 [:db_insert_placeholder_3] => cck:field_item_location:1059 [:db_insert_placeholder_4] => 1000 ) in location_save_locations() (line 974 of /var/www/website.com/sites/all/modules/location/location.module).

Despite the specific table in that example, we get this error on other tables.

Here is my situation. I have taken a large University project. At any given time there are 50,000 campus residents who use the system daily.  In addition to that, I am migrating 100s of 1000s of items of content both manually and through custom module code (migration from the old university data) to this new Drupal 7 site.

This error is killing us, to the point where we are almost ready to scrap the last years worth of work and go with something else if Drupal cannot handle this type of load.

But that is more or less my question -  How can Drupal handle this type of load?  How can I organize my work flow to be able to handle this much activity? Is this a Drupal issue? A database issue?

Specifically, I am running Ubuntu, LAMP stack 16GB RAM. I am open to any suggestion whether it be Drupal related, database related, server config related, or a different work flow to work within Drupal's capabilities, so feel free to suggest anything if you have experience with this much activity.

I work for Stanford university and have been doing similar things. We constantly have to load over 100,000+ nodes on a regular basis. We have been working on our own custom loading code for 2 years now have been able to speed up the process quite a big using pcntl_fork. The only thing you have to remember is to close all socket connection before invoking the fork. For example you have to close you mysql connection, memcache connection and even mongo connection. Drupal will automatically create new connections when one doesn't exists. As far as the deadlock problem, we were able to fix that issue by putting innodb_locks_unsafe_for_binlog = 1.


When user is registered to drupal site ,disable admin approval notification I want to disable admin approval notification when user is getting registered to a drupal site. I don't want to send notification mail to the admin.

You can disable the administration approval option in configuration page /admin/config/people/accounts of your site.

Otherwise, if you wish to maintain adminstration approval but only disable the email, add the following line at your settings.php:

$conf['user_mail_register_no_approval_required_notify'] = FALSE;

Links: Disable register email notification


Disable cache on base url for redirecting unauthenticated users I am trying to redirect unauthenticated users. So anytime an unauthenticated user tries to get to the base url, redirect them to an external url. Currently works, but continues to redirect to the external url even after user is authenticated and logged in. So I am trying to disable cache whenever the base URL is accessed.

Here is my current code for redirecting in my src/EventSubscriber/RedirectAnonymousSubscriber.php file:

class RedirectAnonymousSubscriber implements EventSubscriberInterface {
  private $redirectCode = 301;

  public function checkForRedirection(GetResponseEvent $event) {
//    to kill page caching:
//    \Drupal::service('page_cache_kill_switch')->trigger();
    $is_authenticated = \Drupal::currentUser()->isAuthenticated();
    $route_name = \Drupal::routeMatch()->getRouteName();

    if (!$is_authenticated && $route_name !== 'user.login') {
      $response = new RedirectResponse('https://example.com', $this->redirectCode);
      $response->send();
      exit(0);
    }
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkForRedirection', 30);
    return $events;
  }
}

Would that would be the correct way to go about things? And how would I go about implementing that in my *.routing.yml file and elsewhere?
Thanks!

Not Drupal specific, but you should use the status code 302. Redirects with a status code 301 are cached very aggressively by browsers.

In Drupal custom code, never send a response directly, set it in the event, so that it can be returned and cached properly by Drupal, which is by the way not a bad thing, because the page cache can handle different cached versions for authenticated and anonymous users:

$event->setResponse($response);


How to see #default_values in multiselect form I've done a custom form that is a multiselect type form. When I edit the node, the options that were previously selected are not shown in the selected options part.

This is the code that I've done:

 foreach ($node->field_tem_tica[LANGUAGE_NONE] as $delta => $value) {
    $term2 = taxonomy_term_load($value['tid']);
 }

  $query2 = "SELECT name, tid FROM taxonomy_term_data WHERE vid=4 AND language = '$language_url';";
  $result = db_query($query2);
  foreach ($result as $row2) {
     $options3[$row2->tid] = t($row2->name);
  }

  $form['group_config']['tematicas'] = array(
     '#type' => 'multiselect',
     '#title' => t('Temáticas'),
     '#options' => $options3,
     '#required' => TRUE,
     '#multiple'=>TRUE,
     '#default_value'=> $term2,
     '#prefix' => '

',
     '#suffix' => '
',
     '#size'=>20,
  );

Does anybody see a mistake? Is there any way to see the default_values?

Thank you.

The default value needs to be the key of the options array, so assuming the rest of your code is correct, this should work:

$form['group_config']['tematicas'] = array(
  '#type' => 'multiselect',
  '#title' => t('Temáticas'),
  '#options' => $options3,
  '#required' => TRUE,
  '#multiple'=>TRUE,
  '#default_value'=> $term2->tid,
  '#prefix' => '

',
  '#suffix' => '
',
  '#size'=>20,
);


In panels, does the right region get its argument from the left? I plan to have a panel page with two regions:
- on left, a panel of one author
- on right, a view of all the stories written by that author.

I don't yet know how the user arrives at this page (my understanding of panels is still in its infancy).

Does the right panel get its argument from the left panel? Or somewhere else?

If the left panel node has Node ID 62, does the view (right panel) need to be sorted in node ID order (with a contextual filter)?

It gets its context from the Contexts that you load into the Page on the Page Manager part of the dialog. It looks like this:

In this case I started to override the node view page, so it comes with the initial context of the node (nid, date published etc).

I then added a relationship on that same page of User to bring in the related Author's User data. After I saved it brought that context in for me and it looks like this:

Note the User from Node part.

I can continue to bring in context connected to the node, or now also connected to the user.

To embed a view in a Panels pane you need to first install Views content panes which is part of CTools. You then add a Content Pane via the Views UI to the view. You set the Contextual argument and in ADDITION you need to click on argument input (middle part of the Views UI) to tell the view where the context is coming from. This dialog will then bring up your contextual argument that you added, and a selection for you to specify where or what to get the context from. For the most part you will select From Context and for a node select Node, Content id. Now back in your Panels UI you can add a view as content. You select View panes (though this is just a default that is specified on the view itself and you can alter it per view), select your view, and it will pick up the contextual filter and the type of context you specified for it, and automatically make a selection of contexts that match that you have enabled in Page Manager.

So in order to decide what panel needs what context (or arguments) you need to first establish how the content in the specific panel is related to the type of page your are creating a variant for. I your case of author and stories, you can start with a user page and you want to end with stories on that user page written by the user. Your initial context will be User. No need to bring in extra context as your view for the right panel will take a uid contextual filter. Your right panel will embed a Views content pane with a contextual argument of uid that you connect as the author of the nodes. You will specify in that view that you want the argument input to be of User type from Context, and in your panel, when you add the content pane it will allow you to link it to the user context that is available.


MarkupInterface interoperability with other PHP frameworks Situation in Drupal 8

Drupal 8 introduces a few classes and interfaces for safe markup:

Drupal\Component\Render\MarkupInterface
Drupal\Component\Render\FormattableMarkup
Drupal\Core\StringTranslation\TranslatableMarkup

The purpose is

to mark a string as being safe for use in html, without further sanitization.
to have the string be lazy-evaluated.

The problem seems to be that all of these are specific to Drupal.

Use case

I am designing an API I want to publish as a composer package, that should be used and implemented within Drupal 8 but also work outside of it. It should not depend on anything within Drupal.

There are interfaces that can return string labels, or arrays of such labels (e.g. to act as option labels in a select element).

Implementations within Drupal will want to use the t() function, which returns TranslatableMarkup objects. But the interface or the calling code know nothing about Drupal's TranslatableMarkup or MarkupInterface.

Solutions considered so far

One option would be to require all implementations to return plain strings, which they can do via (string) cast, or by calling the __toString() method. This would work but it feels unnatural.

Another option would be to introduce a custom TranslatableString object which my own API can understand. This would replace a Drupalism with a my-own-ism, and also feel clumsy for implementations within D8.

Another option would be to allow the interface to return arbitrary values and later attempt to convert them to strings using either a flexible adapter layer, or attempting to call the __toString() function. This would make it harder to require a specific return type, and detect if an implementation returns "illegal" values.

Question

Have there been any attempts to make a "bridge" between Drupal's MarkupInterface (EDIT: And TranslatableMarkup) and the larger PHP ecosystem?

Ongoing discussion

There are some comments below which point to interesting directions.

I'd say the main question is still open: How can we bridge the Drupal-specific classes and interfaces to the outside world? Are there Drupal-agnostic versions of these classes and interfaces?

TLDR

(this summarizes conclusions from the comments below)

The MarkupInterface is available on packagist as part of the drupal/core-render package, which provides all the classes from Drupal\Component\Render\* without any heavy dependencies (only drupal/core-util). It does not give you TranslatableMarkup, though.

If you let your package depend on drupal/core-render, you can use MarkupInterface as a return type.

Implementations within Drupal modules, which call t() and return a TranslatableMarkup object, would satisfy the return type from the interface.

Implementations outside of Drupal would instead return FormattableMarkup, or HtmlEscapedText, or a custom implementation of MarkupInterface. Or something else, if the interface allows alternative return types (e.g. native string).

You need to decide if you accept this dependency, or do something else instead.

Original (longer) answer

The ultimate goal of having the two names spaces in Drupal is

Drupal\Component is for classes that do not need a bootstrapped kernel.  In other words, these do not need a running Drupal system. These classes may depend on other classes outside Drupal\Component (eg, Symfony) or other classes in Drupal\Component, but not Drupal\Core
Drupal\Core is for classes that require a bootstrapped kernel.  These full from Drupal\Core, Drupal\Component, and elsewhere.

Take date/time objects.

DrupalDateTime is in Drupal\Core because leverages the translation service.
DateTimePlus is inDrupal\Componentbecause it adds some enhancements to the native\DateTime` class.

So, in theory, Drupal\Component can be used in anything. That said, the composer.json files for each component may not be accurate for dependencies and minimum PHP version.

In your case, MarkupInterface and FormattableMarkup should be able to be used outside of Drupal. TranslatableMarkup relies on the Drupal translation system, which needs a booted kernel to operate.

TranslatableMarkup essentially just extends FormattableMarkup, and acts a bridge to the string translation service. So, that on its own doesn't buy you much unless you need everything that surrounds translation (language management, the UI, etc).

All of that said, I am not sure how much you will really gain from this. Ignoring the translation parts, FormattableMarkup is a component, but they are really best used as part of the rendering service, which is part of core.  For the purposes of making your own API, I would start with seeing if you can just leverage FormattableMarkup on its own.


Defining functions in a module and calling them from a controller I want to use a function in both a controller and a module. where should I define that function?

Can I call a function in module from a controller? How I can do that?

This is exactly the case when you define a Service:

In your controller you call the service with Dependency injection
In your module you call the static \Drupal::service('..')


Stop rendering custom entity label in view mode I have declared a custom entity with a schema with a few fields on which is all working as I expect.

I want to remove the label when rendering the entity so have tried the following.

Added some view modes to the entity info hook and although I can see that they exist when I go to manage display none of my entity fields appear. Not sure if this is how it should work or not.

Any ideas?

The below function stops a custom entity label from being rendered based on the view mode.

function HOOK_entity_view_alter(&$build, $type) {
  if($type == 'YOUR_ENTITY_TYPE' && $build['#entity_view_mode']['view_mode'] == 'YOUR_VIEW_MODE'){
    $build['#page'] = TRUE;
  }
}


Altering relationship in Views contextually I need to alter a Views relationship contextually: since the View is embedded into another node, the relationship is defined by a field's value of a parent node.

I presume the only way to add a relationship is using hook_views_data_alter, but I'm not quite sure if it's going to work inside a preprocessor function (I'm creating a View for a certain node type) and what's the proper way of using it. The related field will be a Nodequeue instance (Nodequeue module is integrated with Views using relationships), its name will be contained in that parent node's field.

Thanks in advance!

I did eventually discover simple solution, so perhaps it comes in handy for anyone else later. views_data_alter, of course, is not meant to apply an existing relationship, but rather to create a new one. To apply an existing relationship programmatically - Nodequeque in my case - you need to call in add_item function of view class:

$view->add_item($view->current_display, 'relationship', 'node', 'nodequeue_rel', array('names'=>array('myqueue'=>'myqueue'), 'required'=>1, 'limit'=>1))

where an array is a set of options like: the name(s) of queue(s) and whether any nodes excluded from chosen queque(s) should be added (1 - bool - implies that only nodes inside the chosen queque will be added).


Can you do branching multistep forms in ctools? I'm using the ctools multistep form code in a couple of places in a project, and would like to branch the user's path through the form.  That is, in step 1, I get some stuff from the user that allows me to determine that the user should be sent to either steps 2a, 2b, and 2c, or 3a, 3b, and 3c.  I've been looking but haven't yet found anything out there about this; are branching multistep forms in fact possible with ctools?

Yes, branching logic can be done.

If your validation/submit handler for step 1 sets $form_state['clicked_button']['#next'] = '2c, your next step will be 2c.

There are a few gotchas, which may or may not surface depending how your forms are intended to be used, whether they allow stepping backwards, etc.

All your steps should at least be in $form_info['forms'] so the wizard knows how to load them.

Note however, that if step 2c is not in $form_info['order'], the default "trail" generated by the wizard will not have any of the steps highlighted as it can't figure out where 2c fits in. Likewise, the next/previous steps around 2c may not be the ones you intended if 2c is not listed in the normal flow order.

The wizard basically pre-populates #next on your buttons based on '$form_info['order'], and then pushes that value into $form_state['redirect'] in its own submit handler, so you have complete control of which step is next. You could manually override $form_state['redirect'], but the wizard should be able to manage it for you.

If your step progression is basically linear but you only want to "skip ahead" based on the selection in step 1, this works fine as you can simply add all steps to $form_info['order'] in your page callback (or where you defines $form_info) and doing the next/back logic in your validation/submit handlers. The user will see all steps listed in the "trail" but may skip some depending on your conditional logic. (The back button also has #next set to say what it goes back to.)

If your step progression is truly branching and a fixed order including all steps would not make sense, I would recommend to hide the trail and re-implement it yourself using the logic which determines which steps go in which order.


Is there a standard place 3rd party module pages report what PHP version they're tested on? Is this info reported anywhere?

for e.g.
https://www.drupal.org/project/optimizely

or

https://git.drupalcode.org/project/optimizely

There is a route for all modules of the pattern https://www.drupal.org/node/{nid}/qa for showing testing reports.  Nightly runs, per-commit runs, and one offs should appear there.

For the module you mentioned, the page is https://www.drupal.org/node/1305958/qa, and it looks like automated tests aren't set up.

The Poll module does show tests, https://www.drupal.org/node/1896974/qa

In general, the default test (if set up) will track the min versions for PHP and MySQL for the chosen core branch.


Drupal 7.9 and flexible images Drupal 7.9 re-introduces height and width attributes to images - I understand this helps improve front-end performance, but it's giving me problems while using flexible images in the vein of responsive web design.

This is the same issue as whitefleaCH mentioned on this post: How can I prevent height/width attributes on images run through the theme system?

Using max-width in CSS still scales images, however the height remains as what was defined in the markup. Does anyone know how to either correct this in CSS or remove the height/width attributes from images all together?

Check out theme_image():

foreach (array('width', 'height', 'alt', 'title') as $key) {
  if (isset($variables[$key])) {
    $attributes[$key] = $variables[$key];
  }
}
return '<img' . drupal_attributes($attributes) . ' />';

So you need to clean width and height as top level keys but also from the attributes array:

function mymodule_preprocess_image(&$variables) {
  unset(
    $variables['width'],
    $variables['height'],
    $variables['attributes']['width'],
    $variables['attributes']['height']
  );
}

And yes, in Drupal 7, Variable process functions can now be used for all theming hooks. Don't forget to clear your cache so the new preprocess function is picked up.


How to create something like a textual "add other term" for taxonomy terms? How can I setup taxonomy terms so that you can have an extra field called "others", where you can add your own terms if the term you want to use is not defined yet as a term of that taxonomy?

I have researched and came across a module called Select(or other). It does what I want, but it is in text.

My problem now is that I've added so much taxonomies for my student record content type (like countries, or faculties). So I've gone too far and cannot cancel (undo) the taxonomies and replace them with the module I found.

Any suggestion of how to add something like such extra field to the existing taxonomy module?

I imagine that when users insert data, they might not find appropriate terms to choose from. So I want to give them an option that "if current term don't apply to you, then please insert your term manually".

I'm still newbie in Drupal7 and PHP programming.

When you go to your Taxonomy Vocabulary ([your_domain]/admin/structure/taxonomy/your_vocabulary) you can click on Manage Fields tab and add any field you want. Or go to [your_domain]/admin/structure/taxonomy/your_vocabulary/fields.


Rule for when content is published? I have the scheduler module installed, and i am using rules to notify users when new content is published.

The scheduler module is working perfect, i enter a future date and time for the content to be published. The content is published on the exact date and time.

Rules cannot action on this because there is no event coming with rules that allows me to perform some action when content is published, only when content is saved.

So my question is, how can i rules perform an action when content is published in a future date?

thanks in advance

I believe you are looking for something like this module

  Rules: when Triggers won't do, use the event-condition-action paradigm of Rules. More complicated to set up than Trigger, but very powerful. Revisioning adds its own events and conditions to Rules, for example "content is about to be published" and "content has pending revisions".

and

  Revisioning is integrated with Rules, adding a number of revision-specific conditions and events.


hybridauth module - redirect problems after connect I am using Drupal 7 And the hybridauth module.

In the past - everything worked great, and new & existing users could connect with Facebook and with Twitter.

Now, I have a problem that no one is able to connect with facebook or twitter.

The "closing..." window is stuck for a long time (looks like refreshing itself all the time - like a loop). When I close this "closing.." window, it looks like the user has succeed to login, but I get a message in a repeat many times that says "You have already registered this identity". When this issue is happen - I usually see that the user is finally login - after this long process and many messages (not a clean connect). It's looks like the problem is mainly on the connection to facebook.

Does someone knows what is the problem, and how can I fix it?

dblog errors:

TYPE    hybridauth
DATE    Friday, March 28, 2014 - 18:16
USER    user name
LOCATION    http://www.example.com/hybridauth/window/Twitter?destination_error=home
REFERRER    http://www.example.com/hybridauth/window/Twitter?destination_error=home
MESSAGE Exception: User profile request failed! Twitter returned an error. in Hybrid_Providers_Twitter->getUserProfile() (line 77 of  /home5/mysite/public_html/sites/all/libraries/hybridauth/hybridauth/Hybrid/Providers/Twitter.php).
SEVERITY    error

Here is another db log, that looks fine here, but caused a stuck "closing.." window that refresh itself all the time:

TYPE    user
DATE    Friday, March 28, 2014 - 19:00
USER    user name
LOCATION    http://www.example.com/hybridauth/window/Facebook?destination_error=home&destination=home
REFERRER    http://www.example.com/
MESSAGE Session opened for hybridauth_Facebook_6003111111.
SEVERITY    notice

We had the same exact issue using the above configuration.

It turned out that I had a rule enabled to redirect the user to a page upon login.

When I disabled the above rule everything went back to normal

Probably a conflict between modules.

Thanks,
Leonidas