How to get the uid of a newly created user? I've been searching for this for ages, but could not come with a solution. Drupal 7 provided a way to get the uid of a newly created user after running user_save; the new user has been added and the uid has been returned in the object. However, now in Drupal 8 when I use the User::create() method, it only returns a constant based on whether the user has been created or updated. Is there any way to get the uid after the user has been created though? I don't seem to find a way. Any help is appreciated.

Where are you creating the user? Could you use entityTypeManager and EntityStorage instead of User::create()? I have the following in a method in a custom entity:

$storage = $this->entityTypeManager()->getStorage('user');
$owner =  $storage->create(['mail' => $email, 'name' => $this->getName()]);
$owner->save();
$uid = $owner->id();

If you don't have access to entityTypeManager() in your class, you could alternatively use:

$storage = \Drupal::service('entity_type.manager')->getStorage('user');


Drupal 7 contexual filter display block based on node reference I have been going around in circles with this for a few hours now... Time to ask for help!!

I have two Content Types:

1: Book

2: Reader

The Book Content Type has a node reference field which is a select list of readers create with the Reader Content Type.

This is all set up and working fine.

Now the issue with my views:

I have a view with is a block containing the Reader fields. What I want to do is have it when the Book node is loaded my block shows underneath with the referenced reader details. Also if no reader is referenced then no block shows up.

I have spent some time in Relationship and Contextual Filters but can't get it to work.

The book URL is formatted like this:

books/[book-title]

I tired using 'raw value from url' in Contextual Filters as setting it to the 2nd argument but that didn't work either.

If anyone can help me out here I would be very much appreciative.

Thanks
C

Here is what I would do if I am understanding this correctly:

Create a new view block

1.) Create a view with Filter critera:  Content type is book
2.) Then I would create a Relationship to: Content Reader
3.) Add all the fields and add a relationship to the Reader content type (whatever you want displayed from the reader content)
4.) Add a contextual filer with: Content NID, where it says WHEN THE FILTER VALUE IS NOT AVAILABLE click on the Provide default value radio and select Content ID from URL
5.)  Add that block to the story display page wherever needed


Is there a way to expose the pager fields? I'd like to let the user pick how many items are gonna be displayed on the page. Therefore, I need to display a field with a select or something.

Is there a way to make that directly through the UI, not with coding?

Yes, you can do that with Views.

In the pager settings for the View, select to expose the number of items to the user.

Make sure the textfield with available items per page options includes the default number of items per page.


How to combine block form submit result with on fly created content together in Drupal 8 I write a custom module in Drupal 8.

Have my custom block defined:

class MyBlock extends BlockBase {
    /**
     * {@inheritdoc}
     */
    public function build(){
     $form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\myform');
     $markup = bunch of html here;
     $content = data feed from 3rd party;
     return array(
      '#markup' => $form + $markup + $content,
     );
  }
}

What I want is, that after block build have both form and feed data in format html way show up.
Any suggestions will be appreciated.

There are two ways you can do this. You can put the results in the form, or you can put the results in the block. Choosing which one to do will depend upon how the form should work - if you were to use this form in another location, and would want the results to show in that location as well, then you should put the results in the form as follows:

function some_form(array &$form, FormStateInterface $form_state) {

  // Note: Form build not shown.

  $results = some_function_that_returns_results();
  $form['results'] = [
    '#prefix' => '
',
    '#suffix' => '
',
  ];
  foreach ($results as $result) {
    $form['results'][] = [
      '#prefix' => '
',
      '#suffix' => '
',
      '#markup' => $result,
    ];
  }

  return $form;
}

If you only want the results to show if the form is in the block, and not in other places where the form would be shown, you add the results to the block as follows:

public function build(){
  $form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\myform');
  $markup = bunch of html here;
  $content = ‘some data’;

  $block = [
    'form' => $form,
    'markup' => [
      '#markup' => $markup
    ],
    'content' => [
      '#markup' => $content,
    ],
  ];

  $results = some_function_that_returns_results();
  $block['results'] = [
    '#prefix' => '
',
     '#suffix' => '
',
  ];
  foreach ($results as $result) {
    $block['results'][] = [
      '#prefix' => '
',
      '#suffix' => '
',
      '#markup' => $result,
    ];
  }
}


Which module will allow me to see the two buttons "Customize this page" and "Change the layout"? When I use the Drupal distribution Openchruch, and I view a page as an administrator. There are two buttons in bottom:
customize this page
and
change the layout

Which module will let these two buttons appear?

Panels and "Panels In-Place Editor" (sub-module of panels)


Yes you can do by using Views Merge Rows module.

  Sometimes when you use relationships in views you get a number of rows
  with the same content in some of the fields. This results in a huge
  table (grid, list, etc.) that affects the usability of your view. The
  Views Merge Rows module provides a way to combine rows with the same
  content in the specified fields.


Any modules for editing files in the browser? I need a way to edit any file in my template directory, but not through a local editor and then by using FTP, but by using my browser. I was wondering if anybody knows a Drupal module or another product that lets you do this.

Well, elFinder, and this page may help you. At least elFinder supports inline file diting. Good luck!


target=_blank for links in view I've got a view and one of the fields is displayed as a link. (Output this field as a link is cheked). But now i want those links to have target=_blank attribute.

How can i achieve this?

When you check Output this field as a link there is a Target input box available (Further down). In that input box you can write _blank. (D7)


Multiple pagers on same view page When creating a view whose display type is page, we got an option to apply pagination using pager option given in view, where you get sort of radio buttons to select pager, full, mini, etc..

Do we have check-boxes instead of those radio buttons?

What If want to render 2 different pagers in my view display - full and mini?

Any help is really appreciated.

There is the Expose items per page option under Pager options, so this might help a bit. This allows users to change how many results they want to see per page.

Why do you want to show different pagers for the same set of results? Pagers can add to the performance strain.

There are some contributed modules that add to the Views pager, try searching for them and see if they come close to what you need. For example Pagerer or Views Extra Pagers.


Views contextual filter pages and duplicate content? I just picked up a site that has its content represented by views pages with contextual filters instead of content pages, meaning that the content is available in two places. For instance, mysite.com/node/282 and also mysite.com/find-a-store/georgia/282-node-title. The pages that are utilized on the site and linked to via the main find-a-store page are the views ones, whereas the node pages seem to just sit there as sources for the view.

Is this a circumstance where there would be SEO penalties for having duplicate content? Will search engines even readily pick up on these views pages at all? Would it be better to change this so that the content is only available on the content page? I think it would be simpler to manage metatags/paths/redirects by using the content pages instead of views, as well.

For removing them from Google search, you could use the Metatag module https://www.drupal.org/project/metatag to mark nodes of that Content Type as noindex.

For internal Drupal search I suggest adding the Custom Search module https://www.drupal.org/project/custom_search You can use that to block searching of that Content Type.


Taxonomy menu block order I have a Taxonomy Menu Block, displaying the whole tree of a taxonomy category.

However if I change the order of the taxonomy terms it does not affect the Taxonomy Menu Block. Does anyone know if it is possible to make the Taxonomy Menu Block sort the terms in the order they are sorted in the taxonomy tree..? An illustration of the problem:

My menu block is showing:

Item A
Item B
Item C

If i then go to the tree of taxonomy terms and move Item C above item B like this:

Item A
Item C
Item B

the Taxonomy Menu Block still shows:

Item A
Item B
Item C

if this module does not respect the order, try to make a view and use its block. see here: https://stackoverflow.com/questions/3806028/drupal-taxonomy-block-vocabulary-listing


Save node when content with reference to it is created I have two content types - Review, and Business. Reviews have an entity reference field linking the review to the Business being reviewed. On the business page, I have fields that display the averages of the submitted reviews for different aspects of the Business. However, the average only updates itself when the node is saved. So, I need a way to automatically save the business page when a review referencing it is created. I'm assuming that the best way to go about doing this would be using Rules, but I am not sure what actions to assign to the Rules to make it tick. Any suggestions?

in rules (sorry the terminology is not exact) :

action : node save
condition : type = review
select the bussiness from the review
resave that business (you will have to force it probably)

or the same in a hook (node_api, operation save, nodetype review)

the best would probably be creating an agregated view end embedding that into your node (or attaching with a block, many possibilities)


How to add SSL site seal in drupal? I have got site seal from positive ssl but cant figure out where to insert it.
Their support option says inset the code in the html body tag. Its very vague for drupal, at least for me to understand because i dont have much knowledge of the drupal internal structure. Can anyone help please?

You can just insert it in a Block. just goto Structure > Block > Add Block and enable full html input and just copy and pate. Then just assign that block to where you want it to show up.


Find role based on list of permissions Is there any way of finding the role given a list of permissions?

I.E.:

$permissions = array('administer content', 'access content');
$role        = find_related_roles();

// $role = array(4 => 'client')

Something like this should do it:

  $permissions = array('administer content', 'access content');
  $query = db_select('role', 'r')
    ->fields('r', array('name'));
  $alias = 'rp';
  foreach($permissions as $perm){
    $query->innerJoin('role_permission', $alias, 'r.rid='.$alias.'.rid');
    $query->condition($alias.'.permission', $perm);
    $alias = $alias . 'a';
  }
  $result = $query->execute()->fetchAllAssoc('name');

It's doing separate inner joins with the role_permission table for each permission, to ensure that the role has all the permissions.


How to display an entity property 'type' with form api 'type' for display in a form and then setting with the submitted value? Is there is process/ function that maps data types that you can use in entities (specifically custom entities using the Entity API) to form #type options? This is to dynamically add a field to a form from the entity and then once I've got the value from the submit handler, use the wrappers to set the property on a entity of the same entity type. Or am I taking the wrong approach here?

I am trying to get an entity property type and am currently using...

$property_info = entity_get_all_property_info('MY ENTITY TYPE');

Which generates $property_info['field_postcode'] which has this value...

field_postcode      Array [10]
    label               Post Code
    type                text
    description         Field "field_postcode".
    getter callback     entity_metadata_field_property_get
    setter callback     entity_metadata_field_property_set
    access callback     entity_metadata_field_access_callback
    query callback      entity_metadata_field_query
    translatable        false
    field               true
    required            true

There I can see that it's got a 'type' of text which seems to translate well to a textfield in the Form API. But what about something like "file" in the Form API?

I wonder if I'm missing a piece of the puzzle here.

In response to Clive's comments under my question I have setup a project on drupal.org and issue to the Entity module issue queue as adding this functionality appears to be the best action. This would be the first contribution I've made so I'm eager for others to take on co-maintenance.

After I've thought a bit on how to go about doing this (still very open to suggestions) I'll add code etc. For the time being Clive's suggestion of using Entity module might be right but I've not yet checked it all out.

In the meantime, here is the code I was using (just as a fairly straight-forward form callback) with a form and call_user_func_array() passing through the callback the user would have used. That's just in a basic custom module I called entity_to_form because tbh that's all I know how to do at the moment).

code:

/**
 * Form callback
 *
 * @param entity type, existing entity type as in entity_load() $entity_type
 * @param callback, as in call_user_func_array() $callback
 * @param array, as in call_user_func_array() $param_arr
 */
function entity_to_form_new_form($form, &$form_state, $entity_type, $callback) {
    // if not a valid entity type, set error and return
    $info = entity_get_info($entity_type);
    if (!is_array($info)) {
        global $user;
        $variables = array(
            '%uid' => $user->uid,
            '%timestamp' => time(),
            '%callback' => $callback,
            '%param_arr' => json_encode($param_arr),
        );
        watchdog('entity_to_form', 'callback not existing: error during function
            entity_to_form_new_form() timestamp = %timestamp, uid = %uid,
            callback = %callback, param_arr = %param_arr', $variables,
            WATCHDOG_ERROR, $link = NULL);
        drupal_set_message('An error occurred and processing did not complete',
            'error');
        return;
    }
    // if not a valid callback, set error and return
    if (!function_exists($callback)) {
        global $user;
        $variables = array(
            '%uid' => $user->uid,
            '%timestamp' => time(),
            '%callback' => $callback,
            '%param_arr' => json_encode($param_arr),
        );
        watchdog('entity_to_form', 'callback not existing: error during function
            entity_to_form_new_form() timestamp = %timestamp, uid = %uid,
            callback = %callback, param_arr = %param_arr', $variables,
            WATCHDOG_ERROR, $link = NULL);
        drupal_set_message('An error occurred and processing did not complete',
            'error');
        return;
    }
    // get information about the entity properties and custom fields
    $property_info = entity_get_all_property_info($entity_type);

    // dynamically set elements for the properties and custom fields

    // fullfil the final requirements for the submit handler
    $form['entity-to-form']['submit-callback'] = array(
        '#type' => 'value',
        '#value' => $callback,
    );
    $form['entity-to-form']['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );
    return $form;
}

/**
 * Form submit handler
 */
function entity_to_form_new_form_submit($form, &$form_state) {
    $callback = $form_state['values']['submit-callback'];
    $variables = '';
    call_user_func_array($callback, $variables);
}


Keep the URL alias for a node when using href I am using Drupal 6 and I have set aliases for my nodes under Administer > Site building > URL aliases. This works properly; for example, I have alias = about/faq, node = node/33, and when I click on my menu the page shows up properly on the browser address bar as about/faq.

The problem I have occurs when I want to reference my node from hyperlinks placed in a page on the website (or any other website). I want to use
 instead of
 so that I don't have to change the href if I later decide to change the alias. However, when I do this, the page shows up as http://mywebsite.com/node/33 on the browser address bar.

I was wondering whether it would be possible to have it show up as http://mywebsite.com/about/faq on the address bar instead.

You can use global redirect so that it does a 301 redirect to the aliased url.

I would recommend you additionally use path redirect so that you can keep old aliases and redirect them to the new one. That way you don't even have to worry about using the unaliased url.


Pre-process drupal_goto or use hook_exit to stop redirect I want to unit test some drupal custom modules but the drupal_goto() function is causing problems by creating header errors (e.g.: PHP Warning:  session_start(): Cannot send session cookie).

My question is, is it possible to stop the drupal_goto() function from redirecting to the destination page or somehow tap into hook_exit() to return the $destination.

I've tried something like (in addition to exit and die, but it stops the PHPUnit tests:

function custommodule_exit( $destination = null ) {
  return $destination;
}

Any help is appreciated.

This is most often caused by UTF-8 with BOM. Check your editor and change the file format if it is.

The only way to redirect in hook_exit() is another drupal_goto(). Be careful that you don't create redirection loops.


How can I conditionally display something in Views header area depending on the argument in URL? The URL of my page view looks like my-view/%1/%2
The first argument %1 is term id of either vocabulary A or B or C and all of them are hierarchical taxonomy.

How can I conditionally display something in Views header global text area depending on which vocabulary %1 is or if it's parent term or child term?

I don't know if it's standard practice to answer such an old post, but another solution may be helpful to those who don't want to do any coding.  You can conditionally attach a header by using Views Attachments. This may not be the best practice for a production site, but that's another discussion. This answer is just to let you know of the possibilities.
Add an Attachment display for each Vocabulary you want a separate header for, and set their properties according to the images below. Notice that all attachment properties are overridden, in order to not affect your main Page or Master (default) display.
Edit: The images displayed below are for Views 3.x. Hopefully, they are helpful for Views 2.x, as well.

Add Attachment:

Add an attachment for each header you want displayed conditionally (as shown above).

Attachment Filter:

The above filter will ensure no records are displayed by the attachment, only the header.

Contextual Filter (1/2):

Set the contextual filter for each attachment (as shown above and below).

Contextual Filter (2/2):

Set the term to be used for this attachment (my example is "Glossary"). Be sure Action to take if filter value does not validate is set to 'hide', so that only the desired header is displayed.

Attach To Page:

Be sure to attach your attachment to something (here, attached to the "Page" display). Click on Global: Text Area to set your header.

Set Global: Text Area (in Attachment Header):

Click Global: Text Area (prev image) and set your desired header. Notice: still overridden. Also be sure to check Display even if view has no result since the filter for the attachment excludes all records.

Page/default Contextual Filter:

Last, but not least, set the Contextual Filter for the main page itself (not an attachment) according to your needs.


How can i access only the text of a comment? In the comment.tpl.php there is

<?php
    print render($content);
 ?>

and this converts to this html

THE COMMENT

What can i do if only want text "THE COMMENT" printed and not all this html?
I know $content is an array but can't find a way to dig into it's elements.

Install devel and try dpm($content);

This will give you an easy way to browse that array.


Moving title into Content Type node? I'm currently building my first Drupal theme (have experience in other content manager systems) and just have a quick question regarding normal practice...

So, I have a number of different templates for a website theme I am building

Home > Level 1 > Level 2 > Article

I have created Content Types for each of the different templates e.g

*node--level_1.tpl.php*, *node--level_2.tpl.php*

By default it seems that the page's title is printed in page.tpl.php.

My plan is to delete the title from page.tpl.php and render it where appropriate within the node templates.

My question is simply is this ok? Is this normal practice? And are there any implications/consequences of doing this?

It's worth saying the reason for doing this is that on some levels there is no title, and often when the title exists it has to rendered under an image (so printed under the custom image field).

Obviously one issue I instantly thought of is that for default pages such as /user the title won't be printed. Could I use some logic in page.tpl.php to say print the page title only if it is not printed within the content type node template?

Thanks for your time!

Scott

I'd say go ahead - your plan to remove the Title from the page template and print it instead in the node template makes sense to me. I've done similar things in the past.

One thing you may want to look into is creating a custom page template for your content types, in addition to your node templates. This will give you even more control over your final rendered page on a per-content-type basis. This could help you avoid inadvertently removing the title from other pages, eg. your Front page.

Here's a quick function you can add to your theme's template.php file that will get Drupal to look for a custom page template (eg. *page_node_yourcontenttype* for each content type.

/**
* Tell Drupal 7 to look for a custom page template for each node type.
*/
function YOUR_THEME_NAME_preprocess_page(&$vars, $hook) {
    if (isset($vars['node'])) {
        $suggest = "page__node__{$vars['node']->type}";
        $vars['theme_hook_suggestions'][] = $suggest;
    }
}

Please note that I didn't write this particular snippet, but I have done the exact same thing successfully. Check out http://leepowers.net/drupal-node-custom-content-type-page-template (not my site) for the original snippet with a nice explanation.

Hope that helps!


Apply settings to all display overridden and default in views 3 I want to add a field to a views having around 10 displays, I want to apply it for all display but I get two option 1) this page 2) all display except override! How can apply it for all display either overridden or not?

Note, If I apply it all display it only applies to default displays and I still have to do this for overridden displays. I need a quick way to add a field to all displays whether its overridden or not.

Thanks

Once its overridden there is nothing you can do to affect it globally.

I guess you could export the view and just add the field to the export code and then import the code.


Apache SOLR + Facet API + Taxonomy terms I want to create a product catalog and I have been told that apache SOLR could be the best way to go. I installed Drupal Commerce, Apache SOLR Integration (7.x-1.0-rc2) and Facet API (7.x-1.0).
I added a custom field "category" to my product display content type which refers to a hierarchical taxonomy vocabulary.

Clothing

Tops
Dresses
Skirts

Accessories

Bags
Jewelery

Shoes

Pumps
Sneakers

On my products page I would like to see a facet block where I can select my categories.
I want to show my top level categories without their children at first, but when you select a category I also want to see its' children. You can achieve this functionality with the standard installation I believe.

BUT when I select one top level category (Clothing) my other top level categories disappear (Accessories, Shoes).
I don't want to be able to select multiple top level categories at once, I just want them to be visible...
Is that possible in any way?

Although I've not tried the recipe I believe that this article over at wunderkraut is an exact match for what you are after. There is a lot of custom coding involved.


Simpletest db table cleanup Everytime I run simpletest it creates tables that it does not clean up.  Is there anyway to tell drupal to automatically clean these? I looked in my db today and there are hundred of misc unecessary simpletest tables.
Thank you

That only happens when the test is aborted (e.g. fatal error inside the test class) so that Simpletest isn't able to do the cleanup.

There is a button called "Clean environment" at the bottom of the test overview page and a message telling you about that button when a test is aborted.


How to get Term ID by its custom field? I'd like to get Term ID by its custom field. I would like to do this using EntityFieldQuery().

Here's what I have so far:

  $query = new EntityFieldQuery();
  $entities = $query->entityCondition('entity_type', 'taxonomy_term')
    ->propertyCondition('vid', '1')
    //I need help with this line:
    ->fieldCondition('field_foo', $fieldValue)
    ->range(0,1)
    ->execute();

Update - I'm providing screenshots to make it more sense.

Here's a view of the custom field

I'm basically trying to get "myTermName" Name field, by "myValue" Foo field.

There is undefined value in fieldCondition. there are some examples listed below. try one of these format.

->fieldCondition('field_foo', 'tid', array('12','13'), 'IN')
->fieldCondition('field_foo', 'value', 'spotlight', '=')
->fieldCondition('field_foo', 'fid', 'NULL', '!=')
->fieldCondition('field_foo', 'tid', $value)
->fieldCondition('field_foo', 'value', $year. '%', 'like')
->fieldCondition('field_foo', 'value', NULL);


List All vocabularies and their terms How can i list my vocabularies and their terms in this way . Is there a module that can help me to do this . or i should go with custom VIEW and jQuery.

thanks :)

You can do with Taxonomy Term Reference Tree Widget module.

  This module provides an expandable tree widget for the Taxonomy Term
  Reference field in Drupal 7. This widget is intended to serve as a
  replacement for Drupal's core Taxonomy Term Reference widget, which is
  a flat list of radio buttons or checkboxes and not necessarily fit for
  medium to large taxonomy trees.


Remove wrapping div from field type radios (Drupal 7) I am trying my hand at theming form output and am stuck on radios. I am attempting to remove the div that wraps a set of radios,

div.form-item > div.form-radios > div.form-type-radio > input[type="radio"]+label
                ^^^^^^^^^^^^^^^ <- Remove that

I have a sample form:

function no_name_form($form, &$form_submit) {
    $form['radios'] = array(
        '#type'    => 'radios',
        '#title'   =>'Question text',
        '#options' => array(
            '1' => t('yes'),
            '0' => t('no')
        ),
        '#theme'   => 'no_name_radios',
    );
    return $form;
}

and I register the theme functions for both the radios group and individual radio buttons:

function no_name_theme($existing, $type, $theme, $path) {
    return array(
        'no_name_radios' => array(
            'arguments' => array('element' => NULL),
        ),
        'no_name_radio' => array(
            'arguments' => array('element' => NULL),
        ),
    );
}

Then I define the theme functions:

function theme_no_name_radios($variables) {
    $element = $variables['element'];
    $attributes = array();
    if (isset($element['#id'])) {
        $attributes['id'] = $element['#id'];
    }
    $attributes['class'] = 'form-radios test';
    if (!empty($element['#attributes']['class'])) {
        $attributes['class'] .= ' ' . implode(' ', $element['#attributes']['class']);
    }
    if (isset($element['#attributes']['title'])) {
        $attributes['title'] = $element['#attributes']['title'];
    }
    return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';
}

function theme_no_name_radio($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'radio';
  element_set_attributes($element, array('id', 'name','#return_value' => 'value'));

  if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-radio'));

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

When I use even the stock code from Drupal 7 to build the theme functions, the radios come out blank, and at this point none of the code has changed.

Ultimately, I want to end up with this:

div.form-item div.form-type-radio > input[type="radio"]+label

I am not sure where I went wrong.

The div.form-radios is set by the theme wrapper of the radios. Use this code to prevent the theme wrapper from adding the additional div:

function no_name_form($form, &$form_submit) {
  $form['radios'] = array(
    '#type'    => 'radios',
    '#title'   =>'Question text',
    '#options' => array(
        '1' => t('yes'),
        '0' => t('no')
    ),
    '#theme'   => 'no_name_radios',
    '#theme_wrappers' => array(),
  );
  return $form;
}


Delete confirmation as popup I have a view containing saved user webform drafts set up in a table format.  I have given permission to the authenticated user to delete own submissions.  When clicking the delete link located on the table it redirects user to a separate page asking "Are you sure you want to delete this submission?"  I'd like to accomplish one of two things.

Have no delete confirmation, when the user clicks delete it is immediately deleted. Preferred
Have the delete confirmation page as a pop up.

I'm new to coding drupal modules but I believe I have isolated the code to be found within the webform.submissions.inc folder, line 465 - 467:

$question = t('Are you sure you want to delete this submission?');

return confirm_form($form, NULL, "node/{$node->nid}/submission/{$submission->sid}", $question, t('Delete'), t('Cancel'));

Any help would be appreciated, I have searched and researched and keep coming to the same results.

Use the hook_form_alter hook, check which form you're on and what the current action is, then remove the node and redirect to where you want to go.

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7.x

Here's my D8 code, should be fairly similar in D7:

<?php

function my_module_name_form_alter(&$form, $form_state, $form_id)
{
  if ($form_id == 'node_mynodename_delete_form') {
    // write code here to delete the node and redirect
  }
}

This code goes into the .module file.

Replace my_module_name with the name of your own custom module.

Replace mynodename with the machine name of your node.

There are plenty of examples out there on how to programmatically remove a node and redirect.


Using Rules to Schedule Publishing/Unpublishing of Content I have a Triggered Rule that is fired on "Content is going to be saved". What it should do is look at the content type, and if that passes, delete any scheduled task based on that node ID, and schedule the "Publish Ruleset".

The "Publish Ruleset" then is fired, which calls a Schedule Expire Node rule, and Schedule Node Publish rule. The first one schedules another task based on an Expiration CCK Date field, the second publishes the node based on a Publish CCK Date field.

Anytime these rules are fired, any other scheduled tasks with the same node ID are deleted.

Some times nodes are published when they should be, some times they are not, and they don't seem to be unpublished with consistency either.

Is it too specific to have the CCK Date fields using time as well as date for the rule? Should it just be a date without specifying time?

I am having trouble figuring out if this is the correct way to automate the publishing and unpublishing of content with Rules.

I modelled the Rule after this tutorial:

http://drupal.org/node/520012

What I am seeing is sometimes the tasks are scheduled correctly, and the nodes in question are published (or unpublished). The queue never seems to clear itself though. Does Rules know that it can't publish something that is already published, or does it evaluate everything in the queue anyway?

Has anyone found a good way to handle this?

I've had a great experience using Scheduler to schedule publishing and unpublishing of nodes automatically.

Although this doesn't specifically answer your question because it doesnt involve rules, its worth mentioning :)


How can I avoid  the "The file x.jpg is in use and cannot be deleted." warning I get when I try to delete a media file? On the page admin/content/media I'm trying to remove a file, and I get the following warning:

  The file x.jpg is in use and cannot be deleted.

We've been struggling with this issue for some time now, and it looked like the root of the problem was related to the list of revisions in the node the file was in. Deleting the revisions enabled us to delete the file.

Has anybody experienced this issue? Is there a way to fix it?

It's not a great idea for us to have to remove all previous revisions of a node in order to just delete some duplicated files from the media library.

To be honest this is the behaviour that should be expected of the field/revision system.

If you have an image file that is attached to a node revision, Drupal (rightly) makes sure that another process in the system cannot delete it. If this wasn't done you'd end up with incomplete/erroneous node revisions.

The only options you've got (in terms of the UI anyway) are either deleting the revisions (which you already know about), or removing the reference to the file from the revision(s) in question.

If you're feeling brave you could dive straight into these tables and make the changes manually:

node
node_revision
field_data_field_FIELDNAME
field_revision_field_FIELDNAME

But I strongly advise you only go down that route if you really, really know what you're doing, and have a good backup system in place :)


Form Permissions not working in Module with Multiple Forms This works great in a module with a single form, however in a module with multiple forms the form does not show up in the permissions list. Is there something that I need to do differently for modules with multiple forms?  For example, do I need to add security to each form before it will recognize it for any forms in the module?

I add this to hook menu:

'access callback' => 'user_access',
'access arguments' => array('Spring Grove Scorecard Access'),

Then use this function:

function form_scorecard_permission() {
    return array(
       'Spring Grove Scorecard Access' => array(
       'title' => t('Spring Grove Scorecard Access'),
       'description' => t('Allows users to access the Spring Grove Scorecard.'),
    ),
  );

This was my fault for not completely understanding how the permissions function worked.  I didn't realize only one function is needed to house all form permissions.  The following code works great.  Hopefully it will help others who aren't all that bright like myself:

function glatfelter_supplier_action_register_menu() {
  $items = array();

  $items['sar_performance_form'] = array(
    'title' => 'SAR Performance',
    'description' => 'SAR Performance Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('sar_performance_form'),
    'access callback' => 'user_access',
    'access arguments' => array('QCA SAR Performance Form Access'),
  );

    $items['sar_sdr_form'] = array(
    'title' => 'SAR SDR/NCR',
    'description' => 'SAR SDR Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('sar_sdr_form'),
    'access callback' => 'user_access',
    'access arguments' => array('QCA SAR SDR Form Access'),
  );

  return $items;
}

//***PEFORMANCE FORM***
function sar_performance_form($form, &$form_state) {

   //Display the overview
   $form['fs_sar_performance_overview'] = array(
     '#type' => 'fieldset',
     '#title' => t('Overview'),
   );

   $form['fs_sar_performance_overview']['sar_performance_overview'] = array(
     '#markup' => t('Performance form overview goes here'),
   );

   //Display the form
   $form['sar_performance_something'] = array(
     '#markup' => 'Form input can start here',
   );

   return $form;
}

//***SDR FORM***
function sar_sdr_form($form, &$form_state) {

   //Display the overview
   $form['fs_sar_sdr_overview'] = array(
     '#type' => 'fieldset',
     '#title' => t('Overview'),
   );

   $form['fs_sar_sdr_overview']['sar_sdr_overview'] = array(
     '#markup' => t('SDR form overview goes here'),
   );

   //Display the form
   $form['sar_sdr_something'] = array(
     '#markup' => 'Form input can start here',
   );

   return $form;
}

//This function adds the forms to the permissions menu
function glatfelter_supplier_action_register_permission() {
    return array(
       'QCA SAR Performance Form Access' => array(
       'title' => t('QCA SAR Performance Form Access'),
       'description' => t('Allows users to access the SAR Performance form.'),
       ),

       'QCA SAR SDR Form Access' => array(
       'title' => t('QCA SAR SDR Form Access'),
       'description' => t('Allows users to access the SAR SDR form.'),
       ),

    );
}


Creating a "Related pages" view which also excludes the current node I want to create a view-block of related articles. The base for distinction is a given vocabulary.

The node which serves as base to such related content list should be excluded from the list.

I couldn't find a way to achieve it with the basic type of view-arguments "Filter criteria". Maybe it is possible somehow with the seemingly more complex types of view-arguments "Contextual filters" ?

If you use Views content panes and Panelizer, then:

Set up the view as a content pane with argument input for the Node ID (Nid). Then, set up a contextual filter for Content: Nid and check the "Exclude" box.
In Panelizer, add the view pane and pass the current node ID to the content pane as a the Nid argument.


is db_insert secure? I'm using the Drupal 7 method db_insert, to insert data into a custom table in the Drupal database. I've read that this is the prefered way, however I've walked through the code and doco and I can't see anywhere which parses the values, or tells me that these values are safe.

Some of the values are coming from the user so I need to check against SQL Injection attacks.

This is the example I was reading, where the Drupal 6 parses the values, and the drupal 7 version does not.

<?php
// Drupal 6 version
db_query('INSERT INTO {vchess_games}
   (gid, timestamps, white, black, state, board_white, board_black) ' . "VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s')",
   $gid, $timestamps, $game['white'], $game['black'], $state, $board_white, $board_black);

// Drupal 7 version
db_insert('vchess_games')
  ->fields(array(
    'gid' => $gid,
    'timestamps' => $timestamps,
    'white' => $game['white'],
    'black' => $game['black'],
    'state' => $state,
    'board_white' => $board_white,
    'board_black' => $board_black
  ))
  ->execute();
?>

The Drupal database layer wraps around PDO and uses prepared statements, so yes, the insert statements are sanitised and protected from SQL injection attacks.

This quote from the Prepared Statements docs says it best:

  The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).

The same is true for all of the database functions in Drupal 7 (db_select, db_delete, etc.). The only one that is still potentially insecure is db_query() which will execute any arbitrary string you pass to it. Even with db_query(), though, you can pass in parameters so your query is safe.

The Database abstraction layer docs have some more information.


How can I retrieve parameters from the path? I have a path

 /step/4?guide=6

How can I get parameters 'guide' and '6'in PHP?

If this is Drupal 8, you can simply do:

$foo = \Drupal::request()->get('guide');


Run module after 'Order status gets updated' Action runs I need to load the order object and run the init function when the order status is updated in Ubercart instead of using hook_menu(). How do I hook into the "Order status gets updated" action?  The order state should be "Payment Received."

Does it have something to do with the following code:

function uc_order_rules_event_info() {
  $events['uc_order_status_update'] = array(
    'label' => t('Order status gets updated'),
    'group' => t('Order'),
    'variables' => array(
        'order' => array(
            'type' => 'uc_order',
            'label' => t('Original order'),
        ),
        'updated_order' => array(
            'type' => 'uc_order',
            'label' => t('Updated order'),
        ),
    ),
);

function hemo_menu() {
  $items['add_listing'] = array(
    'page callback' => 'init',
  );

  return $items;
}

function init() {
  foreach ($order->products as $product) {
    $array = data_array($product->data['attributes']);

    foreach ($array as $property => $value) {
      $product->$property = $value;
    }

    $product->primary_email = $order->primary_email;
    create_directory_listing($product);
  }
}

function data_array($arr) {
  $array = array();

  foreach ($arr as $key => $value) {
    foreach ($value as $key2 => $value2) {
      $chars = array(" ", ",", "'", "(", ")", "__");
      $key = str_replace($chars, "_", strtolower($key));
      $value2 = ucwords($value2);
      $array += array("$key" => $value2);
    }
  }
  return $array;
}

function create_directory_listing($product) {
  $node = new stdClass();
  $node->type = 'directory_listing';
  node_object_prepare($node);
  $node->language = LANGUAGE_NONE;
  $node->uid = $product->order_uid;
  $node->field_order_product_id[$node->language][0]['value'] = $product->order_product_id;
  $node->field_order_id[$node->language][0]['value'] = $product->order_id;

  if (isset($product->attendee_name)) {
    $node->title = $product->attendee_name;
  }
  if (isset($product->institution)) {
    $node->field_institution[$node->language][0]['value'] = $product->institution;
  }
  if (isset($product->lab_group)) {
    $node->field_lab_group[$node->language][0]['value'] = $product->lab_group;
  }
  if (isset($product->address)) {
    $node->field_address1[$node->language][0]['value'] = $product->address;
  }
  if (isset($product->address2)) {
    $node->field_address2[$node->language][0]['value'] = $product->address2;
  }
  if (isset($product->city)) {
    $node->city[$node->language][0]['value'] = $product->city;
  }
  if (isset($product->state_or_region)) {
    $node->field_zone[$node->language][0]['value'] = $product->state_or_region;
  }
  if (isset($product->country)) {
    $node->field_country[$node->language][0]['value'] = $product->country;
  }
  if (isset($product->phone)) {
    $node->field_phone[$node->language][0]['value'] = $product->phone;
  }
  if (isset($product->primary_email)) {
    $node->field_email[$node->language][0]['value'] = $product->primary_email;
  }
  if (isset($product->zip_or_postal_code)) {
    $node->field_postal[$node->language][0]['value'] = $product->zip_or_postal_code;
  }
}

I believe you're looking for hook_uc_order() which runs for several operations, including the update operation which is:

  Called when an order's status is changed.

Assuming your module is called "hemo" you code might look something like this:

function hemo_uc_order($op, $order, $arg2) {
  if ($op == 'update') {
    if ($order->order_status == 'payment_received') {
      // Do something with the $order object.
    }
  }
}

Remember to clear Drupal's cache once you've implemented the new hook or it might not get registered.


With Omega, how to inline branding zone with header zone I want set my branding (logo) zone to 4 cols to the left, and the header zone (8 cols) with the two header regions, inline to the right.

Do I simply do this in CSS? Do I specify the branding and header zone wrappers?

You would just use 1 of the zones, not both. Either move the header regions to the branding zone, or move the branding zone to the header region.
Think of it as zones being vertical and regions being horizontal, if you want some regions inline, they should be in the same zone.


FTP sites/all and sites/default/files files zipped and unzip on server or FTP as is? I have cpanel with hostgator, and it's faster to zip the folder sites/all and sites/default/files and then unzip on the server.

Is that the best way to do things or can it get corrupted?

Is it safer to FTP the files as is from the localhost environment?

My first recommendation is for /sites/all that you use a version control system such as Git/Subversion to save then the pull changes. If you must FTP them, I've found it's just as easy to copy them all over at once rather than unpack on the server, mostly because shared host SSH capabilities are sporadic and semi-functional at best.

Things to be careful of: if you're literally copying over /sites/default/files make sure that any .htaccess files were also copied. Additionally, you'll for sure have to do a cache clear because any css or js files saved in those directories will be unlinked from the current database.


Easy way to copy drush vget variables from one site to another site? I have a bunch of vget variables to copy over to another dev site. What is an easy way to do this? I'm able save it to a file via "drush vget | ack var_name > myfile", but how would i do a drush vset using those variables saved in the file?

The problem here is that the output from a drush variable-get might be an array.  Drush can easily render arrays on output, but drush variable-set does not provide a feature that allows you to provide arrays as input.

The best you can do with array data is to use php-eval:

drush php-eval 'variable_set("var", array(...));'

How do you get the array value to insert in here, though?  Trying to do this directly from the drush variable-get output would be problematic; it would be very tedious to get all of the quoting and escaping right. I would not recommend this for your final solution.

Instead, you might consider using drush_invoke_process.  Something similar to this might work:

drush ev '$v = drush_invoke_process("@remote", "vget", array("var")); $data = $v["object"]; variable_set("var", $data);'

That would probably do the trick for you. However, rather than building up a custom solution to moving configuration from one site to another with Drush, I might recommend that you instead examine the ctools export bonus Drush extension. It can export and import variables nicely, and might ultimately be better suited to your purpose.


Commerce line item not referenced by the orders We have a strange situation here where some Commerce Line Items exist in the database, referencing orders through their order_id property, but that aren't referenced by the order through it's field line_items (field_data_commerce_line_items table). Views listing line items show these although when looking at their respective orders they aren't appearing. It is causing wrong calculation of these view.

Is there any explanation as why these line items still exist and can they be deleted safely?

I can display these line using the following SQL request :

SELECT * FROM `commerce_line_item` cli
LEFT OUTER JOIN field_data_commerce_line_items fdcli on fdcli.entity_id = cli.order_id AND fdcli.`commerce_line_items_line_item_id` = cli.line_item_id
LEFT JOIN field_revision_commerce_line_items frcli ON frcli.`commerce_line_items_line_item_id` = cli.line_item_id
WHERE fdcli.entity_id IS NULL;

[EDIT]
I changed the the request to reference to revision table. It does happens that some lines are referenced in a revision, but most are not.

This typically happens when an administrator adds a line item to an existing order via the order edit form and doesn't submit the form. The line item has already been created, but the order hasn't been updated to reference it. We refer to these as orphaned line items, and they're safe to delete as needed.

I implemented a much better approach with Inline Entity Form, which defers any write action for referenced entities until the form is submitted, but last I tried its line item support wasn't fully functional for the site I was working on. May be better now.


Can't see the "help" hook on the Modules admin panel I'm reading Drupal 7 Module Development and trying to learn module development. I've created their example module 'first' and I'm not seeing the 'help' link.

Here is what I have so far...

/sites/all/modules/first/first.info

name = First
description = A first module.
package = Drupal 7 Development
core = 7.x

/sites/all/modules/first/first.module

<?php

/**
 * @file
 * A module exemplifying Drupal coding practices and APIs.
 *
 * This module provides a block that lists all of the
 * installed modules. It illustrates coding standards,
 * practices, and API use for Drupal 7.
 */

/**
 * Implements hook_help().
 */

function first_help($path, $arg) {
  if ($path == 'admin/help#first.') {
    return t('A demonstration module.');
  }
}

Now then... according to this book, when I install/activate the first module, I should see a () Help link to the right of my module name in the Modules admin panel.

I don't. What could be stopping this link from populating this screen. I get () Help links for all of the other modules. But not mine.

I created a subdomain on my server and installed Drupal to test with a fresh Drupal install. The help link shows up and works on the new install. So now I'm trying to wrap my head around what could be killing it on my other Drupal site? Could Devel? Coder? This is very weird.

You have a period at the end of your path condition.

Try this:

function first_help($path, $arg) {
  if ($path == 'admin/help#first') {
    return t('A demonstration module.');
  }
}


How to change path of taxonomy facet search I am using facet search on my site.  The search paths for taxonomy term facets are of the pattern "search/term-name", but I would like them to be of the pattern "search/term-tid".

Is this possible?  How can I change this?

There is a version for Drupal 6 here: Taxonomy menu with custom path for taxonomy terms

However, it uses hook_term_path, which in Drupal 7 has been replaced by hook_entity_info_alter.

Too see note of how to convert this from Drupal 6 to Drupal 7, see guidelines on Drupal.org about  Converting 6.x modules to 7.x


How to pass an argument into Views for Drupal 7? I'm trying to pass an argument through a block created by a view.

The node is an ubercart product node. I have aliased the paths such as:

node/45 to products/[name]

In contextual filters, I've chosen the filter "Content: Nid"

In the Preview with contextual filters it works with the node id as it should. e.g. "45" but the view doesn't show on the page node/45.

I believe the alias may have caused the problem, but I thought Drupal was designed to have aliases converted to node id's.

In your contextual filter, under WHEN THE FILTER VALUE IS NOT AVAILABLE, choose Provide default value and select "Content ID from URL" under Type.


Determining What Text Editor to Use By Default Based on Site Location in Drupal 7? Okay, so this is something I've been wrestling with for a while. We have several different types of users on our site. For example: Bloggers, Writers (for actual articles), editors, and ordinary users that don't have access to writing blogs or articles.

When a user that falls under the Blogger/Writer/Editor role goes to post on our forum section, he/she is presented with the option of choosing what text editor to use.

What I'd like to do is set things up so that a plain text editor is used by default for the forum, and that a WYSIWYG editor is used for articles and blogs. I don't want to present the user with a choice as to which one to use. It should be a straightforward process.

So what do I need to do in order to define the default text editors?

I use the WYSIWYG module to define different profiles for each text input format and the Better Formats module to define which roles get what input formats on which content types.


New Drupal installation not working beyond front page (not accessing database) I just installed a new drupal 7.39 using drush.
From the browser, I can only goes as far as the front page(welcome page) and no further. I cannot log-in, suggesting that drupal is not accessing the database. The installation went smoothly.
Below is my drush commands. Anything wrong with it?

$ drush site-install standard --db-url="mysql://root@localhost/mydrupal1" --site-name=MyDrupal1 --account-name=my_username --account-pass=my_password

Check if you get the same problem using another browser. If with another browser it works, then it might be a cookie problem, The remedy in that case is to delete the cookie in the browser where you have the problem, and try again. Otherwise read on for other typical reasons (options) ...

Option 1 - RewriteRule and RewriteBase

Check if you can use an URL containing ?q=user or ?q=admin. Refer to my answer to the question "7.26 /admin, /user not found on Localhost" (which is about RewriteRule) for more details on that.

In that answer there is a link to the question about "drupal /?q=user is working but /user not working", for which the accepted answer of that question provides more details about tuning RewriteBase in your .htaccess.

Option 2 - Admin option 'Clean URLs'

I you can use the ?q=adminURL, then try to navigate to /index.php?q=admin/config/search/clean-urls to check the current status of clean urls (if it is enabled or disabled). Make sure "clean urls" is enabled.

Refer to "Clean URL leads to duplicate URL after migration to another hosting" for more details on that.

Option 3 - base_url

Make sure the value of "base_url" is set correctly (in your settings.php).

Option 4 - .htaccess file

Verify if the .htaccess file is present in the directory where Drupal resides (and/or that it is not incomplete or corrupt). If it is missing, then upload it. If needed copy it again from the "Drupal" archive file (.zip or .tar) from Drupal.org again, and just use that new .htaccess file.


Getting the value of a taxonomy term reference field I have a content type (Movie) with a taxonomy reference (Movie rating) for which can get multiple values. I would like to use the template node--movie.html.twig and get the first value inserted in the taxonomy term.

I tried using the following code, but it doesn't give any value.

{{ content.field_rating['#items'].getValue()|first.value }}

What am I doing wrong? In which way do I reference the taxonomy term value?

You get the first item out of ['#items] with a "0":

{{ content.field_rating['#items'].0 }}

To get a field from the taxonomy term, I would use the node object, because you don't know how the render array in content will change if you configure the view mode differently:

{{ node.field_rating.0.entity.term_field.value }}


How to get menu tree from a node to build a customize breadcrumb? I would like to build a custom breadcrumb based on node relation from entity reference. For example there is a book node that has menu hierarchy:

Book
|-chapter 1
|--sub chapter 1.1
|---sub sub chapter 1.1.1
|----#Node with different content type and not included/displayed on Book
      Navigation

The Page Node (sub sub chapter 1.1.1) has entity reference relation with node biblio (for ex)

What I want is when I access biblio then the breadcrumb is displayed like the above tree.

Possible solution:
Write a code using nexus theme on template.php on function:

function nexus_breadcrumb($variables) {

  //$breadcrumb = $variables['breadcrumb'];
  //$node = $variables['node'];

  if ($node->type == 'biblio'){
   // pseudo code start
   // get 'book' node that point to biblio
   // get menu tree from the book node
   // construct the menu tree and assign it to $breadcrumb

   // this is I still not know how to code the section.
  }

  if (!empty($breadcrumb)) {
  // Use CSS to hide titile .element-invisible.
  $output = '
' . t('You are here') . '
';
   // comment below line to hide current page to breadcrumb

  $output .= '' . implode(' » ', $breadcrumb) .
   '';
   return $output;
  }
}

Any help will do. Thank you.

Menu Breadcrumb

  Append the page title to the breadcrumb (either as a clickable url or    not)
  Hide the breadcrumb if it only contains the link to the front    page.
  Generate the breadcrumb from the URL structure if content does    not belong to a menu (7.x-1.6 and older only)

For more details click here

Custom Breadcrumbs

  Many new features have been added including support for Views, Panels,
  Taxonomy vocabularies and terms, paths, and a simple API that allows
  contributed modules to enable custom breadcrumbs for module pages and
  theme templates. These are implemented using optional, independent
  submodules that depend on the main Custom Breadcrumbs module.

  In addition to breadcrumb visibility, this version provides an option
  permitting PHP code snippets to be used in forming the breadcrumb
  titles and paths. Multiple languages are also supported.


#weight doesn't work on submit button I'm trying to add two links on custom user form.
The goal is this links to be displayed bellow the submit button.
I've tried with weight property, but it's not working.

What do I miss?

This is my code:

<?php
      function custom_alter_form_alter (&$form, &$form_state, $form_id) {

        switch ($form_id) {
                case 'user_login':

                $form['name']['#title'] = t('Username');
                $form['pass']['#title'] = t('Password');
                $form['actions']['submit']['#value'] = t('Login');
                $form['actions']['submit']['#weight'] = 0;

                $form['page'] = array(
                '#markup' => '
Login
',
                '#weight' => -10,
                );

                $form['register'] = array(

                '#type' => 'markup',
                '#markup' => '
You don't have an account?
                  Click here
',
                '#weight' => 1,
                );

                $form['password_reset'] = array(
                '#markup' => ' You forgot your password',
                '#weight' => 2,
                );

                //krumo($form);
                break;
            }

        }

This line:

$form['actions']['submit']['#weight'] = 0;

only sets a submit's weight inside actions container.

To push actions to the top of the page, you need to affect it's own weigh:

$form['actions']['#weight'] = 0;

and if you want to move only one button, you can restructure your form by moving this button outside actions container:

$form['submit'] = $form['actions']['submit'];
$form['submit']['#weight'] = 0;
unset($form['actions']['submit']);

Note that this may break some forms that expect submit button in it's exact original place in form structure.


Error when upgrading from 6.22 to 7.8 I upgraded my Drupal site from 6.22 to 7.8 (before that i had upgraded from 5.9 to 6.22).
After I start to run the update I had an error before it's started, apparently related to language:

Additional uncaught exception thrown while handling exception.
Original

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table &#039;TheBIgBrother.languages&#039; doesn&#039;t exist: SELECT * FROM {languages} ORDER BY weight ASC, name ASC; Array ( ) in language_list() (line 2513 of /mounted-storage/home106a/sub008/sc63415-EWDY/bigbrother-israel.co.il/includes/bootstrap.inc).

Additional

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table &#039;TheBIgBrother.languages&#039; doesn&#039;t exist: SELECT * FROM {languages} ORDER BY weight ASC, name ASC; Array ( ) in language_list() (line 2513 of /mounted-storage/home106a/sub008/sc63415-EWDY/bigbrother-israel.co.il/includes/bootstrap.inc).

It looks like your languages table is missing. I hope you backed up your database before starting the update. If you have a backup, try restoring it and retry the update again.


View filter, relative date Is there any way to achieve relative date in Views FILTER CRITERIA?

I need a date between 'first day of' and 'last day of'.

Views Contextual Range Filter Module does not work on Drupal 8.4.x.

The standard date Views filters in Drupal 8 have two options:

A date in any machine readable format. CCYY-MM-DD HH:MM:SS is preferred.
An offset from the current time such as "+1 day" or "-2 hours -30 minutes"

The first is an absolute date.  The second is a relative date string (I don't know why this is called an offset date).

So, add a filter, choose 'offset' as an option, and then enter your relative date.  These work for simple comparisons, and between/not between.

At runtime, the value you entered will be parsed by strtotime(); any date-like string that it will accept can be used.   This means that it will be dynamic and always be relative to when the view is executed and not when the view was created.  php|architect’s Guide to Date and Time Programming has a nice appendix in it about what are parsable values (and some of the quirks).

Keep in mind that you may need to adjust the cache rules for the view to prevent stale data from being displayed.  Also, there is a bug1 regarding time zone handling that has not been committed to core yet, which may result in some weirdness.

1 Barring unforeseen problems, this will be fixed in Drupal 8.5.0.


Same View, different displays, One page, same exposed filters. Possible? I want to list my content categorically within view. The problem is that I want all of it to be filtered through exposed filters.

Here is what Content Type looks like:-

Content Type (MyContent)

Title
Body
Category (it has three categories in it "Category1, Category2 and Category 3". User has to selects one when entering the content)

Now I created a view which lists all of the content linearly (like a normal list) and I have exposed filters on top, which filter the content, but now I am not sure how to proceed when I have to show the content as:-

Any Idea what I should do to achieve this? What should I do in this scenario?

I'll be grateful to you valuable assistance.

Best.

So I solved this by using Attachments in my view.

Each attachment had a separate filter.


How to apply image style in a views-view-fields--[view]--[machine-name].html.twig In a views-view-fields--[view]--[machine-name].html.twig, I have

{% set images = row._entity.field_image %}

{% for image  in images %}

{% endfor %}

I have tried with "|image_style('style')" like so

src="{{ file_url(image.entity.fileuri)|image_style('style') }}

This doesn't work, so what am I doing wrong?

Welcome to Drupal Answers!

You can try something like below in your for loop:

{% set image = {
    '#theme':      'image_style',
    '#style_name': 'your_image_style_name',
    '#uri':        image.entity.uri,
    '#alt':        image.alt
   }
%}

then render the image as {{ image }} without img tag as it is rendered along with img tag.


How do I render search block form in theme template? I've customized the search block in "block--search-form-block.html.twig" and it works using block layout on Drupal 9. Is it possible to render the Search Block directly in page.html.twig?
I've tried this and it giving me error (The website encountered an unexpected error. Please try again later.).

Here are the 3 methods I found.
1 - Use plugin.manger.block to render search_form_block
-- in mytheme.theme
function MYTHEME_preprocess_page(&$variables) {
  $customblock = \Drupal::service('plugin.manager.block')->createInstance('search_form_block', []);
  $variables['content']['custom_block_output'] = $customblock->build();
}

-- in page.html.twig
{{ content.custom_block_output }}

2 - Same as 1 but render a customized search block from block--search-form-block.html.twig.
-- in mytheme.theme - Same as method 1
-- in page.html.twig
{% include '@MYTHEME/block--search-form-block.html.twig' %}

3 - Use Twig Tweak - credit to No Sssweat's Post

install the Twig Tweak module
insert {{ drupal_block(search_form_block') }} on page.html.twig


Why won't my batch finish? I have setup a Batch work which looks the following (dump at run time).

The method called for each batch is a public static method, so that is not a problem.

All operations performs perfectly, my nodes are imported in the system, this I'm sure.

The problem is that the Batch progress bar never reaches the 100% and after a few seconds, goes back and forth forever. This clearly happens after all my nodes are processed.

My finished callback is never called and I'm stuck on the Batch API progress bar for years :-)

Any idea on what I could be missing?

Thank you.

So, nothing was wrong with my batch definition, but I tried to disable the web profiler module and everything gets back to normal!


Saving file to drupal site using drupalgap I am trying to save an image from Android emulator to a Drupal site using DrupalGap, but I am unable to do this.  This is my ajax call which I wrote to save the data to drupal site.

My click function

   $('#page_node_create_submit').on('click',function(){

try {
      var title = $('#page_node_title').val();
      if (!title) { alert('Please enter a title.'); return false; }

      var body = $('#page_node_body').val();
      if (!body) { alert('Please enter a body.'); return false; }

      var filef = $('#page_node_filef').val();
      if (!filef) { alert('Please select file.'); return false; }

     //var datastring = 'node[type]=drupalgap&node[title]=' + encodeURIComponent(title) + '&node[language]=und&node[body][und][0][value]=' + encodeURIComponent(body) + '&node[files][field_filef_und_0]=' + '&fid=47' + '&uid=1';
     //alert(datastring);
     //return false;

      $.ajax({
          url:"http://192.168.1.146/drunew/?q=services/session/token",
          type:"get",
          dataType:"text",
          error:function (jqXHR, textStatus, errorThrown) {
            alert(errorThrown);
          },
          success: function (token) {
          // BEGIN: drupal services node create login (warning: don't use https if you don't have ssl setup)
          $.ajax({
              url: "http://192.168.1.146/drunew/?q=my_services/node.json",
              type: 'post',
              data: 'node[type]=drupalgap&node[title]=' + encodeURIComponent(title) + '&node[language]=und&node[body][und][0][value]=' + encodeURIComponent(body) + '&node[files][field_filef_und_0]=' + encodeURIComponent(filef),
              dataType: 'json',
              beforeSend: function (request) {
                        request.setRequestHeader("X-CSRF-Token", token);
                     },
              error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert('page_node_create_submit - failed to login');
                console.log(JSON.stringify(XMLHttpRequest));
                console.log(JSON.stringify(textStatus));
                console.log(JSON.stringify(errorThrown));
              },
              success: function (data) {

               $.mobile.changePage("main.html", "slideup");
              }
          });
          // END: drupal services node create
          }
        });
    }catch (error) { alert("page_dashboard - " + error); }
return false;

});

But the above code is not working for file field, then after doing some R&D I got to know that first we have to get the fid, then save it.

Below is the respone after creating the fid for the image.

{"fid":"47","uri":"http://192.168.1.146/drunew/my_services/file/47"}

Here my doubt is how can I integrate this response in my above ajax call to save the image in drupal site.

Any help, thanks..

Once you have the File ID, that means you've successfully saved the file to your Drupal site. Next up (typically), you'll want to attach that File ID to a new/existing Entity (e.g. node).

If you are creating a new node, use a POST, if updating an existing one, use a PUT.

New

  /my_endpoint/node.json

{
  type: 'article',
  language: 'und',
  title: 'Hello',
  file_images: {
    und: [ {fid: 12 }]
  }

}

Existing

  /my_endpoint/node/456.json

{
  type: 'article',
  language: 'und',
  title: 'Hello Again',
  file_images: {
    und: [ {fid: 12 }]
  }

}

FYI, the latest version of DrupalGap now supports image fields, so you shouldn't have to write any custom code.


How to prevent closing ctools modal window with ESC? I am using ctools modal window to edit some records with Form API.
How can I prevent closing window with ESC key and the default close button?

I had similar kind of a problem. I had to disable closing modal popup by pressing ESC.
In my case solution was adding unbind for modalEventEscapeCloseHandler for page where I was going to get modal popup:

<?php
      drupal_add_js('
      jQuery(document).ready(function(){
        jQuery(document).unbind("keydown", modalEventEscapeCloseHandler);
      });
      ', 'inline');
?>


Commerce + Views: Distinct on Referenced Product not working I have a Product Display node view which ignores distinct on the query. The goal is to avoid displaying multiple product displays which refer to same Product SKU. I created a relation with the Referenced Product but this did not change anything.

Just use this in filter.

Content: Product Reference:delta (= 0)

which will show only one variation of your product.


Customized User Registration form with Profile fields I'm missing something core to how user registration forms are customized and the data is added to the database and I'm hoping to get a workflow.

I have created about a dozen Profile fields, textareas, radio buttons, select lists, etc.

I have written a module to do a form_alter, and in that module I have laid out fieldsets and containers so that everything is neat and orderly.  For example, for Home Information I have this:

$form['hi'] = array(
    '#type' => 'fieldset',
    '#prefix' => '
',
    '#suffix' => '
',
    '#title' => t('Home Information'),
    );

    $form['hi']['hic'] = array(
    '#type' => 'container',
    '#prefix' => '
',
    '#suffix' => '
',

    );

    $form['hi']['hic']['left'] = array(
    '#type' => 'container',
    '#prefix' => '
',
    '#suffix' => '
',

    );

    $form['hi']['hic']['right'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'container',

    );

and then I have this to display Profile fields that are relevent to Home Information:

$form['hi']['hic']['right']['profile_memberlist']['field_home_phone'] = $form['profile_memberlist']['field_home_phone'];
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#maxlength'] = 16;
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#size'] = 13;
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#title'] = t('Phone');
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#description'] = t('Enter your phone number');
$form['hi']['hic']['left']['profile_memberlist']['field_first_name'] = $form['profile_memberlist']['field_first_name'];
$form['hi']['hic']['left']['profile_memberlist']['field_first_name']['#maxlength'] = 16;
$form['hi']['hic']['left']['profile_memberlist']['field_first_name']['#size'] = 13;
$form['hi']['hic']['left']['profile_memberlist']['field_first_name']['#title'] = t('First Name YO');
$form['hi']['hic']['left']['profile_memberlist']['field_first_name']['#description'] = 'HEY THERE';

Now when I view the registration form, I see first all my generic Profile fields, PLUS the elements created from the above. I thought that unsetting the profile_memberlist was the way to go, but it turns out that while the user is created the Profile fields do not get saved this way.

My Submit is something like this:

$form['#submit'][] ='all_data_form_submit';

the actual function:

function all_data_form_submit($form, &$form_state) {
drupal_set_message('
' . print_r($form_state['values'],TRUE) . '
');

$new_user = array(
'name' => $form_state['values']['name'],
'pass' => user_password(),
'mail' => $form_state['values']['mail'],
'init' => $form_state['values']['mail'],
'status' => 0,
'access' => REQUEST_TIME,
  'field_first_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_first_name']))),
  'field_last_name' =>  array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_last_name']))),

);

$form_state['redirect'] = array(
'node/31890',

array(
  'query' => array(
    'foo' => 'bar',
  ),
  'fragment' => 'baz',
 ),
);

$account = user_save(null,$new_user);

}

But that ends with a DATA INTEGRITY error on submit, because apparently user_save is being called twice?  I remove the user_save and the user is created, but none of the Profile fields get added to the database.

What has worked for me is when both the unstyled and the styled form elements are shown, and I don't use a custom submit handler, the Profile data is saved.

My question: how do I display the styled and neatly organized form elements only, and have the data entered through them get saved to the database?

I believe you're looking for hook_user_presave().

This hook is called directly before the user is saved and the $edit arg will contain all of your form values.

As an alernative, you may look at the Profile2 module


How to prohibit access to a view if the user is not the user in the account path? I created a page view to display forms created by the user on his account.

I added a "Submitted by" context filter to this view to filter the user ID of the logged in user.

My problem :

When I disconnect and reload the page, the view is still displayed. How to prevent access to this page if the user does not match the user of the account path ?

The submitted by is not an access will not do it
I will post all the steps below since I am not sure what you have done (your view is translated in french)
Basically you will have a view of webform submissions with relationship to the user and filter the current user
creating the view

adding the user relationship

adding the current user filter

the finished view with important parts highlighted

the current logged in user should see ONLY their submissions NOW


custom css for content types in Drupal Basing on existing content type (page) I have created another content type (page-without-video).  The only one difference between these two types, is that I am looking to skip a video section in the second one.  The rest should look the same.  After creating the "page without video" content type, I went ahead and adjusted custom css for the newly created content type (basically just changing the node name from "page" to "page-without-video").   From some reason the new content type did not inherit all the css coding of the "page" and has those default weird lines around images etc.  Is it a css problem or maybe I should look elsewhere to fix it?

I will appreciate any help with this.

Use Code per Node module, that is the easiest way to add custom CSS or JavaScript on node page, content type or block...

Look at THIS for other ways to add custom css...


CKEditor is missing when editing a page, but works fine when creating a new page On our drupal 7 site, we have CKEditor installed. It works fine when creating new content, but it doesn't activate properly when you go to edit the same page later. It acts like there is no editor installed and just gives a standard textbox with source.

If I click "Edit Summary", it will usually show up for the summary textbox (though not always).

Why isn't CKEditor showing up for the Body textbox?

Note that I am not selecting "switch to plain text editor". If I do, and if I see CKEditor on "Edit Summary", then clicking "switch to plain text editor" does properly hide the CKEditor for the Summary textfield. Clicking "switch to rich text editor" also restores CKEditor for the Summary, but the main Body textbox still acts like it uses a plain text editor.

New Page - CKEditor Showing

Edit Page - CKEditor Missing

Edit Page Summary - CKEditor Showing (but still missing for the body textbox - not shown in screenshot)

Edit: More details on the exact problem
I found that the reason a New Page loads ckeditor, while editing does not, is because the textbox is empty. If I add text to the new page, switch to 'plain text editor', then try to switch back to 'rich text editor', then CKEditor does not load.

Similarly, if I clear out the data in the textbox while editing a page, and switch text editors, CKEditor loads up.

There is a 500 error being returned, causing CKEditor to not load. When there is text, switching to 'rich text editor' causes an AJAX call to the server to validate or otherwise process the textbox data. Since it fails, CKEditor never loads.

But if there is nothing in the textbox, the AJAX call never happens (and thus no 500 is returned), so CKEditor loads up just fine. This is also why CKEditor loads in the Summary: it has no data.

The solution, in my situation, was two-fold.

Multiple CKEditor versions in different locations

First, the main reason was due to having multiple versions of CKEditor installed in different locations.

When you install the CKEditor module, you must also download the actual CKEditor code separately. It can be installed within the modules/ckeditor folder or in libraries. I had updated the module as well as the code, but the old version persisted in the libraries folder. Sometimes CKEditor would load, and other times it wouldn't. Likely it was due to one CKEditor library loading first.

Removing all duplicate references and clearing the cache worked. CKEditor loaded again on most of our sub-sites.

Buggy code on server causing a 500 error

The second problem was due to faulty php code on one of our subsites. For some reason, an unrelated page included other PHP and was somehow being called when CKEditor made the AJAX call to the server. The server responded with a 500 error, and the error logs shows that this unrelated page was somehow being called and failing.

I took out the reference to the buggy code, and CKEditor worked again for that page.

I still have no idea how that code was being called. It was a simple page with a single line of php, including a different file. Yet CKEditor failed to load on every page within the subsite, not just that page. I chalk it up to lacking enough understanding of Drupal internals.


How to have a webpage File Save As filename different from the page URL? For example - see this BBC News Page: http://www.bbc.co.uk/news/entertainment-arts-16578905

Now Save the page as a web page - notice how the actual filename of the file saved ( BBC News - Golden Globes  Ricky Gervais 'subdued', say critics.htm ) is different from the last URL fragment ( "entertainment-arts-16578905" ).

Drupal has great clean meaningful URL rewriting, I would like to use this as much as possible, so, for me, another example might be e.g. http://example.com/blog/entry-2012-01-17 and the filename could be "mysite.com - blog entry on 2012-01-17.html"

I'm sure that there might be a meta or otherwise setting in the HTML to achieve this, but how can Drupal insert this?

Its actually chrome browser (and some others) doing this based on the page title. For example firefox will actually prefer to save as the last part of the url instead. Make sure to use http://drupal.org/project/page_title module and that should give you what you are looking for. Not sure if there is a way to force it on firefox too.


Can I use view to filter by fields in referenced node? I have 2 node types: Project and Designer.
I have a third node type Contribute with a body that explain the contribute and a field node reference with maximum 2 values that "links" the designer to the project that he contribute.
I can reuse Contribute to link 2 Projects, or 2 Designers, but I can't do this:

In the Designer page I want 2 blocks: one containing the Contribute nodes that link that designer with some Project; one containing the Contribute nodes that link that designer to other Designer s.

With Views I can only create one single block listing all Contribute nodes that links the current node (from URL) to another node, I want to filter from the type or the tags of the nodes referenced in the field.

Thank you.

You want to look at adding Relationship(s) to your View.

You also likely want to look at Views Field View:

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.

Or Views Field:

  Viewfield provides a field that holds a reference to a View and
  renders it whenever the entity containing the field is displayed.

  Features

  Author chooses a view and display from a list.
  View arguments are supplied through tokens.
  Administrators may restrict which views may be assigned.
  Administrators may supply a common value that will be used for all entities in a content type.

Using either of these modules you can figure out your relationships for the views you want and for instance using ViewsField you can add a View to the Designer Content Type with 2 new Views: Contributed Project Nodes views, and a Similiar or Linked Designers View. You can pass the Designers uid as a token to filter these views.


Split blog posts over multiple pages Apologies in advance for the long message but I am very new to Drupal and really have no idea what I'm doing sowill try to explain. My company has there website built in Drupal 7, we have a module installed which allows us to create single page blogs. What we'd like to be able to do is also create blog posts that can be split over multiple pages (if we choose).

As an example, if the user clicked on a particular blog post from our blog page they would be taken to the first page (as they currently do), then, at some point on the page we would like to have a next button which takes them to the second part of the blog post. Then on page 2 they would have the 'previous'/'next' buttons and so on.

I have tried installing a module called Smart Paging which looked like it would do the job, however I cannot for the life of me get it to work. Here is a breakdown of what I have done:

I've installed the module
Enabled it
Selected the 'Default page break method' as 'manual'
Amended the 'text formats' so 'Convert line breaks into HTML (i.e. < br > and < p >) for Smart Paging compatibility' is ticked
Unticked 'Convert line breaks into HTML (i.e. < br > and < p >)'
Added '' to the 'Limit allowed HTML tags' list
Move 'Smart Paging' up underneath 'Body' on Administration » Structure » Content types » Blog entry
Changed the format setting to 'Show Smart Paging settings during content editing of this content type'
Added '< !--pagebreak-- >' to a blog post

I have done all of the above but the blog post still just shows the text that I have written all on one page with no 'next'/'previous' buttons. I'm hoping I've just missed something simple which someone could kindly point out to me.

Thanks in advance.

The core 'book' module will do what you're after.

First, configure the module so that the content type you are using for blog posts is allowed to be in books at admin/content/book/settings.

Second, understand that a book is a bit like a menu, each page is a single node and the book simply provides the links between those nodes in order.  When you create or edit the node intended as the first page of your book go to the 'book outline' settings at the bottom of the node creation form and select create new book.

To add pages, create or edit the nodes that are to be the next page(s) and select the book you just created.

Finally there is a block that the module creates called 'book navigation', move that block to where you wish the 'next' and 'previous' links to go.

Some styling will probably be required if you want it to look like the example you gave.


Commerce (and Commerce Kickstart) rendering add-to-cart buttons on any page? Can someone school me or point me to a resource where I can learn how to render the add-to-cart buttons for specific products on any page? I know how to get them in a view and I'm using Commerce Kickstart.

The goal is simple, for the slider, I'd like to include an add-to-cart button for the slideshow product in the slide itself. The slides are content but they're not controlled by a view as Commerce Kickstart has it's own module for the slideshow. Even if it were a view, I don't think it would help.

So is there a way to print out an add-to-cart (even in PHP) like finding the add-to-cart variable for a product by id or something and just rendering it? Thanks.

Solved: Experimenting I added a product variation field to the Slideshow content type. This essentially creates a new line item type but that's okay. I can now render the field in the view and it adds to the cart like it's supposed to. Just some CSS now and it will be just fine.


Change placement of 'Read more' link in a teaser I have a view where the content is displayed as teasers on the page. There is a 'Read more' link that is displayed above the body text for each teaser (refer to the screenshot below, circled in red), but I would like it to sit underneath the body text instead. Any suggestions on how this can be done?

Edit - 21st of August: Answered my own question below.

I figured out how to move the 'Read more' link to display below the body text for each teaser.
In my Drupal site, I went into 'Structure' in the main administration menu > 'Content types' > Selected the content type I created (in this case, it was: 'Blog post') > Manage display > and then went into the 'Teaser' tab. I was then able to move around the fields so that the 'Read more' link displayed below the body text.


How to update uber cart attribute pricing programatically in Drupal 7? I am using the following code to alter a price, but after being saved, and viewing the node, I don't see any changes.

$node = node_load($nid, NULL, TRUE);
foreach ($node->attributes[4]->options as $attribute) {
    $attribute->price = 4363;
}
node_save($node);

I suspect the problem either being how I am trying to update, or perhaps some caching issue.

UPDATE

I fixed this by running a straight forward SQL query:

UPDATE uc_product_options set price = 333 where oid = 111

But it would still be nice to know how to do this the correct way.


Admin Block Page Custom Theme I am trying to use the garland theme on the blocks page rather than using my custom theme.

I have found this question:
Force block page to use admin theme?

Which has given me a code snippet to use. I have placed this in the modules/block/block.admin.inc file on line 36.

The theme is still my custom theme and i must be doing something wrong. If possible i would rather not use a module.

The code i am using:

function mytheme_init() {
  // Hardcode the administration theme onto the blocks page
  if ($_GET['q'] == 'admin/build/block') {
    global $custom_theme;
    $theme = 'garland';
  }
}

Thanks!

FYI it's a REALLY bad idea to hack core.  Firstly, God knows what could break, and secondly..whatever changes you make will likely be over-written if/when you update core.

To answer your question, you're calling the $custom_theme as you should, but then assigning a Garland to $theme, which isn't used.

Try the following:

function mytheme_init() {
  // Hardcode the administration theme onto the blocks page
  if ($_GET['q'] == 'admin/build/block') {
    global $custom_theme;
    $custom_theme = 'garland';
  }
}

In your custom theme's template.php instead of in block.admin.inc.  Make sure you change mytheme to whatever your custom theme's name is (e.g. my_custom_theme_init or custom_init).

You might also want to look at the Administration Theme module or the Themekey module for admin theme options/theme switching.

Themekey sounds like a pretty good bet for ease of use:

  ThemeKey allows you to define simple or sophisticated theme-switching
  rules which allow automatic selection of a theme depending on current
  path, taxonomy terms, language, node-type, and many, many other
  properties. It can also be easily extended to support additional
  properties exposed by other modules.

EDIT

I forgot, the Admin module also comes with an admin theme option, and a pretty decent admin menu for end users (clients etc.).


Display related content in view by entity reference in views drupal 7 I want to show related content title in block view by entity reference. I have created two content type 1)Hotel Type  2)Room Type. Room Type have field_hotel which references to Hotel Type.
How cant I show content title of Room Type in block except current node.

for eg. RoomA, RoomB, RoomC are belongs to HotelX. I want show link of RoomB and RoomC on page RoomA

I think you could use

Corresponding Entity References for Drupal 7

That way, current node will reference all nodes that reference it - and from this point creating a view is trivial - or you can simply display the field created for back reference, without need for a views module at all.

Other way is to use Views. Create a view displaying nodes from content type A, add argument content reference field > provide default argument > node ID from URL and display this block view on the nodes from content type B.


Remove webform field while edit webform submission I have one webform and need to do that there are 2 fields, TL approval and Manager approval, now if manager submission page will edit by admin then TL approval field should not be load, in short i want to remove specific fields role wise when webform submission will edit. If anyone have an idea about this then let me know.

Try to download & Install Webform Fields Permission module.

Note : Please read comments if you have any query.

If your issue not solved then try once Webform Component Roles module.


Can't create/update resources I can't create/update nodes, taxonomy, users, etc., with Drupal Services. I can log in, retrieve system connection info and log out. Also, I can retrieve a node, user (all details), taxonomy term, index, etc. I have read a lot of internet pages like this, and this, but It doesn't work for me. I have used firefox httprequester, firefox restclient, but nothing changed.

Thouse are the problems I have:

If I send a GET to http:< my path >/node  I get all nodes in json format. Good.
If I send a GET to http:< my_path >/node/23  I get Status 200 Ok but "[false]" returned. The same with .../23.json. But it I put the same url on a browser I get the node in json format.
If I send a GET to http:< my_path >/node?parameters[nid]=23 Then, I get the full json node.
If I send a POST to http:< my_path >/node with X-CSRF-token and with the json right data to create a page, I always get 404 error: could not find the controller.
If I send a PUT to http:< my_path >/node/23 with X-CSRF-token and with the body data to node[title]=Prueba, I get 401 unauthorized: Missing required argument entity (but I'm logued in as admin as system/connec.json said).

I have checked all items when I configured the resources page of the service configuration. I'm using Drupal Commerce Kickstart installation.

What could I do? Thanks.

After lot of search and test I have discovered where was the problem. If I enable Universally Unique ID module, I can't create/update entities. If I disable this module, all works good again. So the problem is with this module.

There is another open question about this issue in this link. So I think I should close this. Thanks.


node_save does not save language I cannot programmatically create a node in anything other than en language.

My site has 3 languages:

en
fr
de

And the code for creating a node is:

define('DRUPAL_ROOT', ...);
require_once DRUPAL_ROOT . 'includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$node = new stdClass();
$node->type = "foobar";
node_object_prepare($node);
$node->title = 'test title';
$node->uid = 1;
$node->language = 'fr'; // *** this doesn't seem to work

if ($node = node_submit($node)) {
  node_save($node);
}

No matter what I type in the $node->language = '...'; the result is always the same. The node is created in the English language. I confirm that via looking at admin/content.

I've even tried stuffing this variable with a proper language object which I got out of the enabled languages of my site:

$languages = language_list('enabled');
$lang = $languages[1]['de'];
$node->language = $lang;

The behavior was an unfortunate side-effect of the admin_language module and the setting Force use of default language.

The "offending" code is at http://drupalcode.org/project/admin_language.git/blob/0167e36c45661502ee6907a5b2b7cad8538b19cf:/admin_language.module#l112

Disabling this options solves the issue.


Error: OAUTH2 SERVER LIBRARY Unavailable I have a website in drupal version 8.3.3 and since I installed oauth2 server module, I get the below error in Admin -> Reports -> Status Report

The OAuth2 server library is required for the OAuth2 module to function. Download the library using composer, downoad it from GitHub or use composer manager.

So I have added OAuth2 server library by running the below command

$ git clone --branch master https://github.com/bshaffer/oauth2-server-php.git

This command executed successfully and also the files are created in libraries directory. But still I get the same error

Note: I followed the instruction from https://www.drupal.org/node/1938218

I encountered the same problem, being new to Drupal 8 development, and this project currently lacking documentation for its use with Drupal 8, probably because it is currently only available through a "dev" edition.

The solution I used was to add the two oauth2-server-php Composer dependencies in the "composer.json" file at the root of the Drupal folder, which are currently:

"require": {
    "bshaffer/oauth2-server-php": "~1.7",
    "bshaffer/oauth2-server-httpfoundation-bridge": "~1.1"
}

Then install them with Composer by executing "composer install".

You can reach the project issue where I got help there: https://www.drupal.org/node/2897289#comment-12202222


How to copy address on node translate action My website is an i18n web site. When it's time to manage content with a location field (address) I need to manually copy the address. Is there a way to make the location copy automatically on translated node?

Let's say I have node type Retail. This node type contains a Location (Field) provide with Location Module for Address purpose.

Use case:

User clicks on Add Retail (in French first). He filled the Location field like (Address, city province, country etc.). After that, the user clicks on save and then clicks on the Translate button. The user chooses to translate in English. The Address field that was previously entered in French is empty and the user needs to enter it again.

Instead of copying the content of the field you can try the Entity Translation module  and only make some fields translatable. It will be much less messy than any kind of copying, where you'll end up with 2 or more copies of data that should actually just be one piece of data.
If you enable Entity Translation on your site you shouldn't enable Translation for this Address field, but you should enable it for other fields that you want to be translated.

Allows (fieldable) entities to be translated into different languages, by introducing entity/field translation for the new translatable fields capability in Drupal 7. Maintained by the Drupal core i18n team.
This project does not replace the Internationalization project, which focuses on enabling a full multilingual workflow for site admins/builders. Some features, e.g. content language negotiation or taxonomy translation, might overlap but most of them are unrelated.

I'm using this on a multilingual website. I don't want the product status field to be translatable:

But the body should be translatable:


Drupal 7 Is the a way to programmatically know the Fields in a Content Type? In Drupal 7, i need to Programmatically create the nodes, by using:

$node = new stdClass();
$node->type = "movie";

After, just this codes above, and lets assume i don't know what are the fields for it.

How can i get to know the fields and that field's structure for this Content Type?
(or) Can i echo out the fields inside a Content Type and its relations ?

field_info_instances(); will get you a list of all field types on a specific entity/bundle.

For example:

$fields = field_info_instances('node', 'movie');
print_r($fields);

Will give you a list of all available fields on the node type of movie.