How to edit image URL in node field? I am using Media Browser widget for uploading and editing images in nodes. My images are stored using image fields. Is it possible to edit URL of the image after uploading? I would need to achieve:

When I upload file named "foo.png" it has by default the following URL:

  /sites/default/files/media/.../foo.png

I would need to edit filename to "bar.png", so resulted path will be:

  /sites/default/files/media/.../bar.png

(only filename is changed in URL)

I tried to edit filename, since it is possible using Media browser widget. But editing filename does not have affect on change of URL for me. I also tried to use following hook: hook_file_presave
I tried to programatically change uri parameter using this hook. But nor filename change neither uri change affected URL of the file.
When I look in directory sites/default/files/..  I can see that filename is the same as I uploaded it, not affecting my later changes of filename or uri. When I load php $file object, I can see $file->filename and $file->uri properties changed.

Is it possible to change URL of the file (just last part of the URL - filename) after uploading the file?

//EDIT: I tried to do following changes in my hook_file_presave:

function mymodule_file_presave($file) {
 if ($file->type != 'image') {
  return;
  }
 if (!empty($file->filename)) {
   $uri_parts = explode('/', $file->uri);
   $count = count($uri_parts);
   $uri_parts[$count - 1] = $file->filename;
   $file->uri = implode('/', $uri_parts);
   $file->destination = $file->uri;
   }
 }

To rename the file, you'll need to use PHP's rename() function. To do so, you'll want to get the file's full local path using drupal_realpath() like so:

// Fetch the local absolute path of our image
$local_path = drupal_realpath($file->uri);

Once you've renamed the file, you'll need to modify the file URI (and potentially other attributes-- use print_r($file) to check).

The wording in the docs is a little weird to me, it says "when a file has been added to the database" which means to me the file metadata has already been saved to the database. However, the example shown in the docs seems to edit this info (but without using &$file ...?) without having to return the file object. Strange.

Anyway, your code might look something like this:

function mymodule_file_presave($file) {
  if ($file->type != 'image') {
    return;
  }
  if (!empty($file->filename)) {

    // Will likely be 'public://'
    $scheme = file_uri_scheme($file->uri);

    // Get full path of image location
    $local_path = drupal_realpath($file->uri);

    // Create new name using drupal scheme format
    $new_uri = $scheme.'new_name_here.jpg';

    // Actual OS rename of file
    rename($local_path, drupal_realpath($new_uri);

    // Update $file object with new uri
    $file->uri = $new_uri;

    // Not sure if this is still needed...
    $file->destination = $file->uri;
  }
}


What is the best practice for having a global collection or set number? I am setting up a content type for a collection of samples. There is already a lot of samples that have a collection number that can't be changed, so I will have to import that data. But My question is how to apply this number; I know its a broad question, but would using taxonomy, or a field in the content type be better?

A field would be better if the collection number must be unique. If so you can activate the Unique Field module to enforce it, then go ahead and import your existing data.

If it does not have to be unique, either will work, but I would still recommend using a text field rather than a taxonomy.


Create URL aliases for Entityform submissions I have the Entityform module installed on a Drupal 7 portal and I've created a new entityform type (let's call it "Preview").

When I land on the list of "Preview" submissions, each submission View link points to [host]/[drupal_base]/entityform/[entityform_id]

What I'd like to get is to change "entityform" term in that url path with something like "preview" term, so that I'll have [host]/[drupal_base]/preview/[entityform_id]

I tried to define a URL alias from the admin configuration panel, but from what I've understood, I can't define an alias with a dynamic [entityform_id] (maybe using a kind of placeholder). Am I wrong about this?

I'm not so skilled in Drupal, so I wonder if there's a way to achieve that result?

Note: This answer only applies specifically for the input form (I misunderstood the question above)

I was able to accomplish this by using simply modifying the entityform made configuration.

Go to /admin/structure/entityform_types
Click on the edit link for the entity form you wish to change
Scroll to the bottom and in the URL path settings set the specific custom paths that you wish
Save

It's that easy and it works for both the preview and the actual form :)


Any easy way to create Login page in Drupal 7 Most of the tuts I found want me to edit the code in template but I am not sure about editing the code, so, thought of asking is there any easy way to create Login Form in Drupal 7.

I don't want to show login block to everyone, and want to put it in some Page and visit it via uri like http://localhost/login then only the login page should show.

So, far I have made a Page called login gave it a title with empty body, Configured user-login block to be shown in content area and be displayed only in login page. So far so good, it looks cool, but the thing is: after logging in I can see the same login page as Blank Page. I did something like the login page would only be accessible by anonymous users but no luck.

My quest is either I should be able to redirect the users to main page after logging in, or have a separate login page instead of using the block which came by default with D7 installation. Any ideas ???

One easy possible way to do this is you can create a node with no content and assign a url "/login" to that node and then assign login block to content region for that page only.


How do I test my code in Drupal 8? I created a Drupal 8 module and I would like know what is the best practice for testing my code?

For example, if I use hook_user_login(), how I can try my code without login/logout every time and how do I display my var_dump() result? (var_dump result not displayed due to redirection after login)

Use Devel for most of the (There is a dev version for Drupal 8) visual testing and seeing output of most of the render arrays (DPM function will retain the array if there is redirect so it will output in those cases). Plus other variables can be output. You can use the old school tail -f drupal_debug.txt by using dd() or just output in Krumo to the screen with dpm(). You can find out more about Devel by visiting the project page.

Also you can run tests using Drupal SimpleTest and find out more about how to implement SimpleTest in the Drupal Examples which does have tests examples for 7 and 8.


Entity Reference get nodes based on tags Let me try my best to make myself understood.

I have a node type Exhibition where I want to display related nodes of type Article, and these related nodes are tagged with taxonomy tags. On the Exhibition node I want a field where I can write one or more words, and related Articles tagged with these words should be displayed.

I want to use the Entity Reference module since this is already in use elsewhere, and I want to limit the number of modules in use. (I know of the Similar By Terms module).

Does anyone know if this is possible?

It can't be done with Entity Reference out of the box, your only option is to install another module or write some custom code (you would need to create a custom widget that searched additional fields on the entity if you went down the custom code route).

One possibility, which seems to be in keeping with your approach, is the Entity Reference View Widget module.  This module allows you to search on any field.  There is a little bit of additional setup since you have to create a view containing your Article nodes, but it means that you can specify your taxonomy as a field that can be filtered.


Load the value of an entity field type in another form I have created a custom field and I wish to load the value dynamically in another form in relation to the specific node entity the value belongs to.
I understand that to get the value I have to use/know the field_name like this

$entity->get('field_name')->getValue();

What I want is to get the field_name set via content configurations with only the type of node and the field name as defined in the fieldItem Plugin

$field_definitions = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('node');

When I dump $field_definitions am able to see all the fields array with all the details but I can't get my node.field_name in relation to the fieldItem name defined in the specific field plugin, in my case field_custom_example

/**
 * Plugin implementation of the 'field_custom_example' field type.
 *
 * @FieldType(
 *   id = "field_custom_example",
 *   label = @Translation("Custom Example"),
 *   description = @Translation("Stores data for Custom Example Field"),
 *   default_widget = "custom_example_widget",
 *   default_formatter = "custome_example_formatter"
 * )
 */

that's where am stuck.

Use the method FieldDefinitionInterface::getType:

  Returns the field type.

  Return value

  (string) The field type, i.e. the id of a field type
  plugin. For example 'text'.

In your case for example:

foreach ($field_definitions as $name => $definition) {
  if ($definition->getType() == 'field_custom_example') {
    // found field $name
  }
}


How to changing Bartik's "Show - Main navigaton" mobile menu message? When you install Bartik and minimize your browser to mobile display you can see the caption "Show - Main navigaton":

I want to translate it to Hebrew so I went to admin/config/regional/translate and typed the stream to change it but found nothing so I guess it's hardcoded somewhere.

Yet, I searched in page.html.twig and menu-block twig but didn't find this stream. I also didn't find CSS language-construct (as in content:x;).

You might know where this stream is located or at least answer with a good way to search it?

You can translate following strings through the core translation system (admin/config/regional/translate):

Show &mdash; @configuration.label
Hide &mdash; @configuration.label

The strings above are defined in block--system-menu-block.html.twig at line 17 and 18.

Furthermore you should translate/rename your Main menu name.


Ajax error and weird white space when connected When connected in Drupal (the problem does NOT happen when logged out), I see a strange � character.

The character seem to break Ajax calls all over the admin (I get an alert, with code 200, and the result of the Ajax request). I get the error when editing views, adding some contents, etc. Anything that requires Ajax.

The character also appears on every pages of the website, but only if I'm logged in Drupal. Otherwise, it doesn't appear.

I figured, the problem can't be in a file, or it would happen when I'm logged out too ?

Is there some files that are only called when logged in ?

Thanks !

Finally found a solution so I'm going to post in case anyone has a similar problem.

First, I made sure I had no unnecessary PHP closing tag, just like Drupal recommands.
I also checked for the character in the database, just in case.

I started commented the page_top, page and page_bottom of my html.tpl.php to see where the problem was.

Turns out, with nothing in the html.tpl.php, (and I mean NOTHING), I still had the character.

I created a random "test.php" with simply an empty  and still had the problem. A similar "test.html" (HTML is the key here), it worked.

Someone had activated a "mod_deflate" in the .htaccess and it seemed to have issues with my version of PHP.

So there it is, hopefully it can help someone.

Thanks !


How to send message using Organic Groups Invite? I am trying to use the Organic Groups Invite module along with the Rules and Message modules to send a message to users containing an option to accept or decline an invitation to a group.

I have set up rules to send a message to the user when they are invited. This all works perfectly, however the message does not contain the accept / decline options that I assume come with the Organic Groups Invite Module.

I am new to Drupal, and since this module has no documentation, I wonder if anyone could help me out with adding the accept / decline option to the message.

Not sure if it is an option you're willing to consider, but the OG Invite People module might be used as a possible alternative for send such invitation to a group. Here is a quote from its project page:

... adds the missing email invite functionality for OG 7.x-2.x.
When you click on "Invite user" a user is created and invited to the group right after. No registration process is needed. Invitee receives an email with one-time login link.


Adding a reference to a bundle in a node I would appreciate suggestion for this common scenario in Drupal 8, which may be different to how I do it in Drupal 6. I don't want to do any programming.

I have two content types: (1) Articles (title, author, body) (2) Authors (First name, Surname, Biography).
Authors are not users.

When adding a new article, I want the option to select either (a) An existing author from a list, or (b) Add a new author to the list, and select it.

When displaying the article, I want to see the author's First Name and Surname, and optionally a Biography teaser, and then the body of the article.

Enable the Entity Reference module that is the part of drupal 8 core.
Create the two content types.

I have two content types: (1) Articles (title, author, body) (2)
Authors (First name, Surname, Biography). Authors are not users.
When adding a new article, I want the option to select either (a) An
existing author from a list, or (b) Add a new author to the list, and
select it.

Add a entity reference field in the Articles content type.
Go to Home Administration Structure(admin/structure/types) click on Manage fields in front of Article content type.Add a new field(Authors) and choose its field type to be Entity reference and after save, The field configuration screen will open.Choose "Type of item to reference" to Content. Then on the next screen choose the reference type(authors content type).

When displaying the article, I want to see the author's First Name and
Surname, and optionally a Biography teaser, and then the body of the
article.

There are several options to do so :
1)Load the authors entity in articles template and display its result like that.
2)Use the Display suite module which is still has alpha available.
3)Create the view block which displays the author information like you want to show.and embed this view in your node article template.
4)Go to Manage Display of that content type(admin/structure/types/manage/article/display) and use a separate display mode to do so.
5)etc....
I would suggest to use the Display suite because I love to use it as it made my life easier at many places.


Updated an empty field collection in Drupal7 New to Drupal and I'm assuming the answer is simple, I've looked through the test suites etc. and still missing the point it seems.

I have a node with a field collection (field_theatre_date_set) that will store a number of dates and times. I have loaded the node and the collection is there but it's empty.

I have used various forms of this and an obvious problem is that the $field_collection_item_value below array structure just isn't there.

Any further pointers greatly received.

$loop=0;
foreach($showing_array as $key=>$value){

 $date='xxxx';
 $time='xxxx';

 $field_collection_item_value = $node->field_theatre_date_set[LANGUAGE_NONE][0]['value'];
 $field_collection_item = entity_load('field_collection_item', array($field_collection_item_value)); // Load that field collection item

 $field_collection_item->field_theatre_date_set_date[$node->language][$loop]['value'] = $date;
 $field_collection_item->field_theatre_date_set_time[$node->language][$loop]['value'] = $time;
 $loop++
}
 $field_collection_item->save();

/**Update***/

Progress has been made. I still have an empty field_collection reference that needs to store a date and time.

I now understand that field collections store a value and a revision_id. I now need to work out how to store these revisions. I have the following code:

$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_theatre_date_set'));

$field_collection_item->setHostEntity('node', $node);
$field_collection_item->date[LANGUAGE_NONE][]['date']   = $date;
$field_collection_item->field_description[LANGUAGE_NONE][]['time']   = $time;
$field_collection_item->save();

Now when I output the field_collection_item I see the following where I am expecting to see the the value and revision:

[field_theatre_date_set] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [entity] => FieldCollectionItemEntity Object
 *RECURSION*
                            )

                    )

            )

And at the very bottom of the array I have the dates and times wallowing on their own:

[date] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [date] => 2014-03-13
                    )

            )

    )

[time] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [time] => 19:45:00
                    )

            )

    )

Any pointers on how to move them into my field_theatre_date_set if they aren't expecting date and time values?

Thanks all for looking!

I believe you need to load and save the node to which the field collection is attached.

This question: Modifying a field collection programmatically missing hostEntity fields is slightly different but the examples are accomplishing the same thing.


How to invoke a custom callback function in Javascript I am trying to just invoke callback in my AJAX response.

Currently I have the following response.

   private function responseWithSuccess($message, $status_code = 200)
    {
        $ajax_response = new AjaxResponse();
        $ajax_response->setStatusCode($status_code);
        $response =
            [
                'status' => 'success',
                'message' => $message
            ];

        $ajax_response->setContent(\GuzzleHttp\json_encode($response));
        return $ajax_response;
    }

It returns a response of the specified format, but is it possible to listen for the response text in this case ?

I've found that I have to use the Drupal Command class that is used for communication.

So I created the custom Command, here is code

class CustomCallbackCommand implements CommandInterface, CommandWithAttachedAssetsInterface
{
    use CommandWithAttachedAssetsTrait;
    /**
     * The content for the dialog.
     */
    protected $message;

    /**
     * Constructs a \Drupal\mymodule\Ajax\BootstrapModalCommand object.
     */
    public function __construct($message)
    {
        $this->message = $message;
    }

    /**
     * {@inheritdoc}
     */
    public function render()
    {
        return array(
            'command' => 'onCustomCallback',
            'message' => $this->message,
        );
    }
}

And add it to response like that

private function responseWithSuccess($message, $status_code = 200)
{
    $ajax_response = new AjaxResponse();
    $ajax_response->setStatusCode($status_code);
    $response =
        [
            'status' => 'success',
            'message' => $message
        ];
    $ajax_response->addCommand(new CustomCallbackCommand($response));
    //$ajax_response->setContent(\GuzzleHttp\json_encode($response));
    return $ajax_response;
}

But when I try to send the request, an error appears.

  Fatal error: Call to a member function getLibraries() on null in
  /public_html/core/lib/Drupal/Core/Ajax/AjaxResponse.php on line 48

What is wrong with my code ?

So basically the main question is how to call specific callback when a response comes back.

P.S.

I know that I could just override default handlers of the Drupal JS module, but I am looking for a better way.

For very basic Commands, you likely do not need to implement CommandWithAttachedAssetsInterface or CommandWithAttachedAssetsTrait.

Here is a good blog post tutorial for a custom Command: https://www.mike-miles.com/blog/creating-ajax-callback-commands-drupal-8

Here is another example: https://www.mediacurrent.com/blog/loading-and-rendering-modal-forms-drupal-8

Here are a couple modules that implement Commands for an example:

iGrowl
SweetAlert

You are not going to want to override core Drupal JS, as it is easy to add your own and communicate to your plugins or third party plugins as demonstrated above.


Why are comments enabled on my content types in Simpletests? When I run Simpletest, it's showing comment forms at the bottom of all the nodes, even though I don't even have the comment module enabled, nor permissions assigned for it. These comment forms showing up in tests is interfering with my tests and I need to disable them, but I don't know how since I never enabled them in the first place.

module_disable(array('comment')); inside setup() does the trick.


How can I add a save button in my page variant? I have created two variants of user edit page, one displays the entire form and other displays only a couple of fields of that form.

I have created a selection rule so that one triggers when is needed and other runs as default form mode.

But the problem is the first variant, which only have two fields doesn't have any save button.

This is what my panels look like:

This is what I did with that variant:

This is a known issue with recent activity => enter link description here

Solution:

After you apply the latest patch to ctools, you need to add a "User form actions / buttons" element to your page.

Your page variant should look sth like this:

And the rendered form now comes with a submit button:

Good luck!


HTTP/2 does not allows to write in folders in Drupal 7, how can I fix? I've recently changed from HTTP 1.1 to HTTP/2, as soon as i did it I was not able to create or edit files from backoffice (both image upload or css/js cache), but if I did it from FTP there is no problem

All the folders are 755 and all the files are 644 and I could not get other informations

Varnich cache is not installed on the server, what can cause the problem?

Solution found, just needed to install suPHP module and configure it so apache could execute php with owner permissions instead of default user


View does not pick up webform submission is from url I have created a block that is to print out the currently displayed webform submission. The problem is that it does not pickup the submission id from the url. It is always displays submission id 11 regardless of what submission you are looking at. Can anyone tell what the problem is how to fix it?

The Details: this is for Drupal 7.19 and using views. My block is set up the following way:

Contextual Filter: Content Nid
Filter: Content NID = 33
Fields: Content NID
        Web submissions: Sid
        Global Custom Text

In global custom text I try and read the nid and sid fields using tokens. The block is only displayed when you view a submission of a specific webform (in this case: webform with node id 33).

Please help as I am desperate here.

Thanks

OK. I see the problem. The submission will be for only one node, so all you need to get the information is the sid. The nid you are looking at is not the nid in the webform submission record. (You will understand in a moment.)

First, delete both the contextual filter on Content:nid and the filter on Content:nid.

Then create a contextual filter using Webform Submission:sid. Under 'When the filter value is NOT available', select Provide Default Value > Raw value from URL, and set the Path Component to 4.

Now to get the correct nid value, you need to create a Relationship on Webform submissions: Node, and check 'Require this relationship'. Now go back to your fields, and edit the Content:nid field changing 'Relationship' to 'Webform Node', and save. Your field should now display as '(Webform Node) Content: Nid (Nid)'. This is the nid found in the Webform Submission record.

Save your view, and you will get the correct values in the block display. I don't know about the token replacements, but it looks like it should work. If not, the Views PHP module will be able to do it without the tokens, using the $row values directly from your view.

Good Luck.


Form does not save value to variable I'm loosing my head. This is the function for generating my admin form:

function section_description_and_images_settings() {
  $form = array();

  $form['images_style'] = array(
    '#type' => 'radios',
    '#title' => t('Set default images style'),
    '#options' => array(
      0 => t('Bootstrap columns'),
      1 => t('Slideshow'),
    ),
  '#default_value' => variable_get('section_description_and_images_images_style', 0),
);

  dsm(variable_get('section_description_and_images_images_style', 0));
  return system_settings_form($form);
}

And variable section_description_and_images_images_style does not store the desirable value. It's always 0, whether I set 0 or 1.

Any ideas what might be wrong?

Variable name is "images_style" in your case


Add foreign key to schema using hook_update_N I've written a module that establishes a child/parent relation ship between magazine issues and the articles in each issue.  The idea is that by associating articles with magazine issues they can all be automatically published on a given date via cron.  That all works fine.

The problem is I'm trying to use a View to list a subset of those articles and list them according the parent issues date, but that isn't showing up as a relationship.  I assume the problem is that I haven't defined a foreign key in my schema.

Is it possible to add one in hook_update_N or whatever?

To clarify, the relationship is created using fields defined in a custom module using the Field API where the parent node has the date info and the child node has a field for the parent NID.

You can add keys to tables using native SQL. It's not supported by drupal 7 core api. I answered this previously elsewhere:
Is there a way to add a foreign key to a table?

I doubt that simply adding a key will expose the relationship for you in Views though.

In order for Views to see this information you likely need to supply the info via hook_views_data() about your custom tables and relationships. A recent blog post I found about this today actually was:
https://chacadwa.com/blog/2014/08/12/adding-full-views-support-custom-entities

From this blog post you can see that for a table that needs a join to add extra fields (and to do so by default in Views) they add the following array to their hook_views_data() function.

// Define a default relationship to the staffdir extra data table.

$data['hank_hrper']['table']['default_relationship'] = array(
  'hank_hrper_extra_data' => array(
    'table' => 'hank_hrper_extra_data',
    'field' => 'hrper_id',
  ),
);

// Now define the staffdir extra data table, so views can use it.

$data['hank_hrper_extra_data'] = array(
  'table' => array(
    'group' => t('Staff directory'),
    'entity type' => 'staffdir',
    'join' => array(
      'hank_hrper' => array(
        'left_field' => 'hrper_id',
        'field' => 'hrper_id',
      ),
    ),
    'default_relationship' => array(
      'hank_hrper' => array(
        'table' => 'hank_hrper',
        'field' => 'hrper_id',
      ),
    ),
  ),
);

// Now we can define fields from the staffdir extra data table for use in the relationship.

$data['hank_hrper_extra_data']['opt_out'] = array(
  'title' => t('Opt out'),
  'help' => t('Allows for users to be excluded from the directory.'),
  'field' => array(
    'handler' => 'views_handler_field_boolean',
    'click sortable' => FALSE, // could be TRUE, but why?
  ),
  'filter' => array(
    'handler' => 'views_handler_filter_boolean_operator',
     'accept null' => TRUE,
    'help' => t('Filter results to a particular result set'),
  ),
);


Main differences between registry and file_registry tables in Drupal SQL tables structure? I already know that in computing in general, registry is the main data structure for paths (whether as a table in DB or a as a standalone DB).

In the case of Drupal, I saw two tables in the DB's. When is "registry" and the second is "file_registry".

While I understand that file_registry table holds paths for files, I wonder what are the main kinds of paths that the "general" registry table holds, and thus what are the main differences between them. I hope a Drupal developer who have dived into these SQL files could explain the main differences,

The file_registry stores entries for all uploaded files as attachments or file_entities to Drupal. Files marked for deletetion are removed at Cron and cleared from the table.

The registry table stores Drupal system information on all available code files available to the system from modules and themes. And more importantly includes all php classes used in the system and where they may be found. When you install or remove modules or themes from your Drupal installation php files are added/removed from the registry table.


Implementation of hook_file_default_displays() {media module} makes it impossible to export image display settings via features This is a issue I am dealing with for days.
It looks like is related to: https://drupal.org/node/1702700

I've created a feature relying on media, file_entity and media_youtube, vimeo... whose main purpose is to embed youtube, vimeo videos etc.

I've correctly set up the file_entity displays weights:
Structure » File types » Video » Manage file display
so that the thumbnails shows ok

    e.g
    "Large filetype icon"   weight: 50
    "Youtube Image Preview" weight: -40.
    {GOOD}

After complete feature export,
"Large filetype icon" weight: 0
"Youtube Image Preview" is set 2.
{WRONG}

I even edited manually the feature's .info and default_displays.inc file with no luck.

Secondly, there are also feature overrides unable to revert.
It looks like somethings alters the file display weights.

The problems comes from the heart of Media module which programatically add default overrides.

I have managed to solve the problem in 2 steps:
(1) Sunk the Media Icon to the bottom

apply a patch to Media module:

--- sites/all/modules/contributed/media/media.module
+++ sites/all/modules/contributed/media/media.module
@@ -1082,7 +1082,7 @@
   $file_display = new stdClass();
   $file_display->api_version = 1;
   $file_display->name = 'video__preview__file_field_media_large_icon';
-  $file_display->weight = 0;
+  $file_display->weight = 50;
   $file_display->status = TRUE;
   $file_display->settings = '';
   $file_displays['video__preview__file_field_media_large_icon'] = $file_display;
@@ -1093,7 +1093,7 @@
   $file_display = new stdClass();
   $file_display->api_version = 1;
   $file_display->name = 'audio__preview__file_field_media_large_icon';
-  $file_display->weight = 0;
+  $file_display->weight = 50;
   $file_display->status = TRUE;
   $file_display->settings = '';
   $file_displays['audio__preview__file_field_media_large_icon'] = $file_display;
@@ -1104,7 +1104,7 @@
   $file_display = new stdClass();
   $file_display->api_version = 1;
   $file_display->name = 'document__preview__file_field_media_large_icon';
-  $file_display->weight = 0;
+  $file_display->weight = 50;
   $file_display->status = TRUE;
   $file_display->settings = '';
   $file_displays['document__preview__file_field_media_large_icon'] = $file_display;

(2) I exported my feature but manually edited the File Display like this:

YOURFEATURE.features.field.inc

For Default the order is

Vimeo
Vimeo Preview
Youtube
Youtube Preview

For Preview the order is

Vimeo Preview
Vimeo
Youtube Preview
Youtube


Sorting a view on a taxonomy term with entityqueue I'm trying to use an entity queue on a taxonomy to create a new sort order for an existing view. But I'm having trouble configuring it.

I've created a dummy website with a fantasy role-playing game theme. I have a content type "Monster" with a taxonomy term "difficulty".

Monsters can have several difficulty tags, but I've created an entityqueue for the subset of tags that I want to sort on:

Finally, I've created the view for monsters, with what I believe are the properly relationships to join in the entityqueue for sorting. Starting with the Monster content type, I've added a relationship to the Difficulty taxonomy term, then another relationship for the Monster Difficulty entityqueue.

Finally, I added the entityqueue as the first sort criteria:

However, the results of the view are still sorting on the title field, "Name", meaning that the sort order of the entityqueue is either not making it in or being respected:

How do I sort a view based on a taxonomy entityqueue?

Edit I removed the sort for the title, as per hotwebmatter's suggestion, but that didn't cause it to sort by the entityqueue.

The order should go Big boss, boss, mini-boss, etc., but it doesn't.

Here are the configuration export ymls of those files different from a vanilla install: https://pastebin.com/r4A94QJ5

I think that the Queue Position sort is being overridden by the Title sort. (In other words, the Title sort may be applied after the Taxonomy term Queue Position sort, making it appear as though the queue is not respected.)

If that's the case, then removing the Title field from the Sort criteria should be enough to get this working.

In case that's not sufficient, here's a good video tutorial on Entityqueue.


Customize Rendered File markup? Wondering how i can control the markup returned for a Rendered file view mode?

This is within a view, i have a field which is a media file image. I set it to use the Rendered File formatter and provide a view mode i created. But i don't see where i can customize the view mode markup.

msvu.jpg

The only markup I want returned is

I want to get rid of the div's and the whole h2 element.

You can create a variation of file_entity.tpl.php from the File Entity module using the following pattern.

file__{file type}__{view mode}.tpl.php

e.g.

file__image__teaser.tpl.php


How do I create an instance of an entity with all its fields attached? I am trying to create an instance of 'commerce_customer_profile' entity with all the extra fields of the customers address.

I am doing this inside a FeedsProcessor that will import users and their addresses from Magento.

I don't want to have to create a fake $form_state array and then use field_attach_submit() as it doesn't seem right to me.

The only other way I have found so far is:

$billing_profile = commerce_customer_profile_new('billing', $entity->uid);
commerce_customer_profile_save($billing_profile);
$full_billing_profile = commerce_customer_profile_load($billing_profile->profile_id);

$entity is the current user being created.

Which will then give me an empty instance of the new entity ready to populate and save but again it doesn't feel right.

Any help appreciated.

for nodes we can do below codes to load all fields and display formatters aplyed on them:

$node = node_load($nid);
field_attach_prepare_view('node', array($node->nid => $node), 'teaser');
$fields = field_attach_view('node', $node, 'teaser');

similar way should be exists for commerce


How can I automatically position a block in Drupal 7 (via a script, Drush, etc.)? I have a bash script that I use to rebuild my dev environment by re-importing my MySQL database and activating/deactivating modules, etc.

Recently, I've realised that I often need the Switch user block provided by the Devel module.

So, ideally, in my script, I'd like to automatically enable the module in the left sidebar.

This question on how to place a block with Drush looked promising but it suggests using Drush Extras, which according to the README does not work for Drupal 7.

How can I automatically set the position of the Switch user block from the command line?

Updated answer:

I just committed https://drupal.org/comment/7000524 to support the Drush block commands in Drupal 7.  I also added a shortcut mode, where arguments can be used in place of options in instances where doing so would be unambiguous.  When calling block-configure from a bash script, though, you should always use the options form; otherwise, your script would break if a specification became ambiguous (e.g. if someone added a block whose delta was named the same as some region).

So, from the commandline:

$ drush block-configure switch_user sidebar_second 10

From a bash script:

drush block-configure --module=devel --delta=switch_user --region=sidebar_second --weight=10

The later works just fine from the command line, of course; it's just more typing.


What are the changes I should make to the .htaccess file to enable clean URLs? What actually are the steps to clean the URL of a site.

I have made the following changes in the /etc/apache2/sites-enabled/000-default file.

<VirtualHost *:80>

    DocumentRoot /var/www
    <Directory />
        Options FollowSymLinks
        AllowOverride All
    </Directory>
    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride all
        Order allow,deny
        allow from all
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
        AllowOverride None
        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
        Order allow,deny
        Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

What are the changes I need to do in a .htaccess file so that I could enable clean URLs?

You do not need to do any edits in the Drupal default .htaccess file to have Drupal 7 enable clean URLs.  Instead, navigate to Home » Administration » Configuration » Search and metadata (its the link named "Clean URLs" on the Admin's Configuration page, and press the button "Run the clean URL test".

If the test is successful, Drupal will make use of its default .htaccess to do the rewrites.  If the test fails, then you need to review your configuration.

Some suggestions:

Make sure that the Drupal default .htaccess is present in your webroot (/var/www).

Make sure that you've actually enabled mod_rewrite for Apache, e.g.:

 sudo a2enmod rewrite

You must also restart Apache after changing defaults, e.g.:

 sudo service apache2 restart

(The example shell commands above are for Ubuntu.  If you run a different dialect of GNU/Linux, you may need to use slightly different shell commands.)


How to add the sum in a Webform Report? I would like to have the total sum of a number field in a report created with Webform Report.

How can I get the total sum of that column table?

Instead of using the Webform Report module, you can use Views and Views Aggregator Plus to display the submission data. You can use the aggregation function sum for the selected fields (to aggregate your webform submission results tables).

Credits: Waluyo Adi Siswanto.


Aggregated entity reference translation I'm having two customs content types in D7, one row (A) and another (B) that aggregates (via entity reference) the rows into bundles of rows (e.g. tables).

I can have up to 40 rows in a table. I'm translating manually each row in several languages.
And then I'm creating one node (lets say node 100) in English of type B aggregating the 40 rows (let's say nodes 1-40) in English, and another node 101 in French (a translation of the English  node 100) that aggregates the nodes 41-80 which are a direct translation of the 1-40 rows.

I would like while adding node 101 in French as a translation of node 100(English) to already pre-fill the node 101 to aggregate the nodes 41-80 which are in french and a one to one translation of the 1-40 English row nodes.

The translated entity reference module cannot help me in my case.

I tried to find a hook for the "add translation" to prepopulate the screen where the node 101 is being created as a translation of the node 100, and then just having to fill in 1-2 other extra fields in French and save...

Now I have to find the 41-80 references by hand, and since I'm having several languages (5 currently) the work involved is immense...

How could I achieve what I need? is there a module already written? otherwise which hook shall I use? I couldn't find an add translation hook in D7 (I believe there might be one in D8).
I just need to know which hook to use for adding a new translation, I think I can manage the rest (finding for each row the translation in the target language).

I also do not need to do anything upon editing the node 101 after it has been saved, thus I only need the hook used the first time the node 101 is being created as a translation of node 100.

Many thanks

The solution was to use the hook_node_prepare($node) and there to check
     if (!empty($node->translation_source))

The above are the conditions that must be filled in to be in the "add translation" event.


Commerce - selecting attribute results in ajax error when product has many attributes I've got a commerce store running well on a Windows IIS server. The only problem is on certain products which contain many attributes (e.g. around 10 or more) the ajax doesn't work when an attribute is selected. The js error in the console is vague as ever:

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /system/ajax
StatusText: OK
ResponseText:

There is nothing untoward in watchdog or in error logs.

The fact that this happens on products with many attributes suggests some sort of PHP limit is being hit, but there are no errors to suggest this. Also worth noting that this is working fine on local/staging server so it's something server based that is the problem here.

Any ideas?

Experienced the same issue. Apache error log "PHP Warning:  Unknown: Input variables exceeded 1000. To increase the limit change max_input_vars in php.ini."

Editing php.ini and setting max_input_vars to a suitable figure fixes this.


A view of full nodes with comments that are a content type I have split up this question into other questions previously trying to join them up to create my final solution. However the combination of what I am trying is causing problems.

I need a comment field to be able to use a CCK field. To do this I am using the nodecomment module as it allows you to use a content type for comment (http://drupal.stackexchange.com/questions/3202/creating-threaded-nodes). I will call this type CustomComment.

I have a custom node type, NodeType. This uses CustomComment for it's comments.

I need to create a view of NodeType. Which prints the full node (not fields). I also need to print the Comments as full nodes as well. Can anyone give any additional pointers. Part of me is thinking It might be better for me code this myself.

First thing that comes to mind:

make a view for the nodeTypes
make a view for the customComments
take the corresponding view-template (depends on your views, check the views theme-information) of the nodeTypes-view and render the customComments-view inside it using views_embed_view()

Maybe there is a simpler approach for that.


How to delete a database field named as a reserved word? I want to drop a field from db table which is named as read.
I tried like;

db_drop_field('my_table', 'read');
db_drop_field('my_table', '`read`');
db_drop_field('my_table', `read`);

None of these work.

Read is a reserved word, but your problem has an easy solution (I test it and works)

Change your field name to reading

And then use:

db_drop_field('your_table', 'reading');


how to get total orders of a user? how can I get total price of all orders which owned by a single user? I want to assign different type of discounts by finding about total amount of their orders.
I'm using

  hook_rules_action_info

.
should I use commerce_order_load_multiple() ?

Try this

$orders = commerce_order_load_multiple(array(), array('uid' => $user_id));

You can use the conditions parameter of commerce_order_load_multiple.


Profile Completeness reminder to the user Hi i need to send an mail reminder to the user whoever not been completed the profile information. Is there any module available  for this? or how do i do this?

Can we do this using rules?

You could take a look at Profile Complete Percent (for core Profile module) Content Complete (if using Content Profile).

If you are using Content Profile, here is an article to assist setting up with Rules: Measure node completion in Drupal, part 3.  I'm sure you could probably get a Rules workflow going with core Profile module as well.


How to restrict number of nodes per content type? How can we restrict number of nodes allowed per content type. Let suppose if we allow 5 nodes then no one including the admin user can add the 6th node of that content type.

Have you tried the Node Limit module?

  The Node Limit module allows administrators to restrict the number of nodes of a specific type that roles or users may create. For example, if a site has an "Advertiser" role that can create "advertisement" nodes, then the node limit administrator can restrict all users in that role to a specific number of nodes. He may also restrict users on a per-user basis.

You could create a role just for node limit and assign ALL users (including the admin) to that role.


Drupal 8 load term by substring Drupal 8 has term method loadproperties which works for custom fields; however, how can I use it (or can I use it) to load by substrings. For example if I have a field: field_full_name and I want to load all terms that start with a string "David*" is this possible ... if not how?

Thanks ~

You can use the SQL operator LIKE in an entity query and append the wildcard % to the string:

$result = \Drupal::entityQuery('taxonomy_term')
  ->condition('name', 'david%', 'LIKE')
  ->condition('vid', 'tags')
  ->execute();

$terms = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->loadMultiple($result);


user/login page displays but gives a 404 error on firebug My Drupal site gives a 404 error in firebug, even though the login form is showing. Also nothing happens when you click Log in-- the page just refreshes and login DOES NOT happen. This only happens in https. There is no error in HTTP and the login is working.

I have installed the secure_login module hoping it might help, but no change. Basically, it just forced the login page to redirect to https.

I thought maybe the https is not configured correctly, but HTTPS is working fine in all the other pages. My site works in both http and https. The only problem is the login form.

The solution is in your Apache config file. Enable ‘LoadModule rewrite_module modules/mod_rewrite.so’ in httpd.conf file and clear the cache and then login again.


Can my site's administrators bypass required profile fields during user creation? I have two separate roles on my site, one for regular users, and one for site administrators.

The regular users must fill out more details about themselves than I need admins to do, such as name, gender and address.

How can I allow the site administrator to create new site administrators without needing to fill out these extra profile fields?

The only easy way I can think of is to make this fields not required. Then the admins can leave it empty.

I'd just let the Admins enter the extra data, even if you don't really need it. Admins are specially trust worthy users. It's not likely that you have a lot of them.

If you must: Create your own form using Drupa FAPI and create a new user by calling user_save in the submit function.


why views items per page set to specific values Why does the Views module accep uses the number of items per page that is in pre-defined sets like 5, 10, 25, 50, and doesn't accept values outside those values?

I know how to change it; I just need an explanation.

To be brutally simple: Because someone thought it to be good UX, maintainers agreed, and no one convinced them other way since then. That's all to it.

There are many reasons for drop-down instead of text field. For example simplicity. User cannot enter bad values, so there is no need for bad value handling. Testing - you can programatically set other amounts, all right, but there you have ones they tested their module for, and take some responsibility that they work properly. Of course, maybe someone simply liked it that way. No way to know for sure what was the most important part in this decision.


Equivalent of node_type_get_types() Can somebody help mi with use of node_type_get_types() in Drupal 8?

Code in Drupal 7

function node_type_get_types() {
  return _node_types_build()->types;
}

Code in Drupal 8

function node_type_get_types() {
  return NodeType::loadMultiple();
}

This was my code in Drupal 7. How to now use node_type_get_types in Drupal 8?

$options = array();
  foreach (node_type_get_types() as $type) {
    $options[$type->type] = $type->type;
  }

Node types are (config) entities, so they have the same methods available as others. Specifically, relevant for you, all entities have id() and label() methods:

use Drupal\node\Entity\NodeType;

$options = array();
foreach (NodeType::loadMultiple() as $type) {
  $options[$type->id()] = $type->label();
}

Those methods are defined on \Drupal\Core\Entity\EntityInterface, you can use them anything that's an entity and that includes almost every type of content and configurable thing, nodes, users, roles, views, image styles, ...


Using a Drupal 6 tutorial for Drupal 7 I hate making posts like this because I feel like I am asking people to do all my work for  me! However, in times like this, when I am pressed for time, I have to. So...

I am trying to add an user profile in the topics in the Forum module. I have found a brilliant tutorial, but unfortunately it is for Drupal 6 and some of the functions are not compatible with Drupal 7; I couldn't find the equivalent functions, and I figured some of you may know them.

If you do, I would greatly appreciate it if you could share them with me; even if you don't provide the whole of the functions in tutorial (which would be nice), and just provide me with the Drupal 7 functions to replace the ones in the tutorial; anything would help.

The main functions that do not work are the profile_load_profile($user), and the get_user_####($user) functions.

By the way, I am assuming it is because those functions are depreciated in Drupal 7 when it says "Undefined"! I can't see any other reason for it not to work, and I kind of expected some of the tutorials wouldn't work properly on Drupal 6.

Drupal 7 doesn't include the core profile module since users are entities which you can attach fields to. If you have added additional fields to the user you can get them with just user_load().

FYI: it is not advisable to the $user when calling user_load() since $user is a global variable which can cause problems.

It doesn't look like that tutorial would ever fully work since get_user_comment_count() is never defined and the get_user_rank() parameter call's for a comment count but uses the $user object in the user_forum_load() function.

To get the comment count of a user you could just lookup the number of comments from the comment table for a given user and the tutorial's user_comment_rank() should still work.


How can I create a birthday calendar using the Date and Calendar modules? I have a content type that represents a person, and this content type has a CCK Date field "birthday". I'd now like to add a list of upcoming birthdays and a calendar where they are displayed.

I'm already using the Calendar module for events on that site, but the birthday stuff seems to be more difficult. I can't use the Birtdays module as I'm working with nodes, not user profiles. And the Date field doesn't seem to support this use case, I can't create a view that only shows upcoming birthdays because I see no way to ignore the year for that calculation.

What would be the easiest way to implement such a birthday calendar?

You can try with Birthdays module. It allows users to add their birthday to their profile.

  The Birthdays module allows users to add their birthday to their profile. It also lists birthdays on a seperate page and in different blocks. Users can receive an e-mail on their birthday automatically, and the administrator can receive periodic reminders of who are having their birthday. Uses Profile module from core.


Is there an alternative private messsage module that integrates with Views? As far as I can tell it's the only real solution on the block. But it has major drawbacks that make it unusable for most sites. Mainly its not built with views, therefore easy customization is out of the question unless I change the code.

Are there any alternatives, paid or free, that beat privatemsg and integrate with Views?

You can also consider theming Private Message.  Private Message is an extremely powerful module that offers a much higher degree of customization than some sites may need (messages can be sent to users + roles at the same time, etc.)

For my site, I added several tweaks to actually limit/reduce Private Message's functionality (users can only have one thread per user, users can only message one user at a time, users cannot send more than three messages in a row to the same user, etc.)

Messaging systems are pretty complex so I found it easier to start with the huge number of options Private Message provides and then reduce them.

You could also help work on privatemsg views integration, though this is a huge project.


Changing a redirect depending on selection Using drupal 7 how can I make a selection alter where a page is then redirected to ? I need the value selected by a drop down menu to be part of the destination url for the redirect.
For instance if I had the following for a drop down menu:

$form['changethis'] = array(
    '#type' => 'select',
    '#options' => array(
      'one' => 'one',
      'two' => 'two',
      'three' => 'three',
    ),

Selecting option 'two'would send the page to www.mypage.com/two

Any help would be great I have experimented with an ajax request and hook_menu_alter , but no luck so far.

You can add your own submit handler to your form. In the submit handler function you will be able to access the value that was entered by the user.

The code could look something like this (to be put in a custom module).

    /**
    * Implementation of hook_form_alter()
    */
    function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
      if($form_id == 'MY_FORM') {
        // Adds our own custom submit handler to the form MY_FORM
        $form['#submit'][] = 'MYMODULE_MYFORM_custom_submit';
      }
    }

    /**
    * Custom submit handler for MY_FORM
    */
    function MYMODULE_MYFORM_custom_submit($form, &$form_state) {
      $form_state['redirect'] = 'my-path';
      $form_state['rebuild'] = TRUE;
    }

Replace 'my-path' with the value the user entered. Look inside $form_state['values'] to find it. Don't forget to check that the value is valid so no funky stuff is done here :)

Good luck.


How to migrate files into a field with unlimited values (D6 -> D7) I am currently migrating a D6 site into D7 and so far everything has gone smoothly. I use migrate and migrate_d2d.

But now I am stuck :-(. I have an image field with unlimited values (a slideshow) and into that field I need to import images from the corresponding slideshow in the legacy site. My problem is that after import only one image is imported (the last one in the slideshow). How do I make every picture end up in its own subfield?
In my prepareRow() I am trying to use the loop below. I fetch the field ID from $row->fields_productimages[#] (index > 2 are field ID's that belong to the slideshow). I then get the file path from the legacy database and use that path to import the image. But as I said, only the last image is attached to my field.
There are no error messages. Any help is appreciated.

$i = 2;
if($row->field_productimages[$i] != ''){
    while($row->field_productimages[$i] != ''){
        $fid = $row->field_productimages[$i];
        $filepath = Database::getConnection($target='default', $key='legacy')->query('SELECT f.filepath FROM {files} f WHERE f.fid = :fid',array(':fid' => $fid))->fetchAssoc();
        $this->addFieldMapping('field_bildspel_instrument')->defaultValue($filepath);
        $this->addFieldMapping('source_dir')->defaultValue('http://www.mysite.se/');
        $this->addFieldMapping('destination_dir')->defaultValue('public://instrument/bildspel');
        $this->addFieldMapping('field_bildspel_instrument:file_replace')->defaultValue('FILE_EXISTS_REPLACE');
        $this->addFieldMapping('field_bildspel_instrument:file_class')->defaultValue('MigrateFileUri');
        $this->addFieldMapping('field_bildspel_instrument:title', 'field_sensorimage:title');
        $this->addFieldMapping('field_bildspel_instrument:preserve_files')->defaultValue(1);
        $this->addFieldMapping('field_bildspel_instrument:urlencode')->defaultValue(1);
        $i++;
    }
}

Finally figured it out. The image field with unlimited values needs a default value with file paths presented as an array. As the array in $filepath was 2 dimensional (an array in an array), I needed two foreach loops to get down to the simple array needed. This is now a working example, I publish it here in case somebody have the same question:

$i = 2;
$filepath = array();
if($row->field_productimages[$i] != ''){
    while($row->field_productimages[$i] != ''){
        $fid = $row->field_productimages[$i];
        $filepath[] = Database::getConnection($target='default', $key='legacy')->query('SELECT f.filepath FROM {files} f WHERE f.fid = :fid',
        array(':fid' => $fid))->fetchAssoc();
        $i++;
    }
    foreach ($filepath as $value1){
        foreach ($value1 as $value){
          $files[] = $value;
        }
    }
    $this->addFieldMapping('field_bildspel_instrument')->defaultValue($files);
    $this->addFieldMapping('field_bildspel_instrument:source_dir')->defaultValue('http://www.myoldsite.se/');
    $this->addFieldMapping('destination_dir')->defaultValue('public://product/slideshow');
    $this->addFieldMapping('field_bildspel_instrument:file_replace')->defaultValue('FILE_EXISTS_REUSE');
    $this->addFieldMapping('field_bildspel_instrument:file_class')->defaultValue('MigrateFileUri');
    $this->addFieldMapping('field_bildspel_instrument:title', 'field_productimages:title');
    $this->addFieldMapping('field_bildspel_instrument:preserve_files')->defaultValue(1);
    $this->addFieldMapping('field_bildspel_instrument:urlencode')->defaultValue(1);
}


How to define template suggestions for node add and edit form by content type? I have a content type Project and it has a more than 100 fields in the node form. The form fields are grouped in different section and category. I tried to use a field_group module to group and categories in different sections, but when I add more than 20 groups field I got a problem in field arrangement and save the changes in form display. Also, i am facing difficulty to theme the form as per the design.

So, is it possible to define template suggestions for node add and edit form by content type and add an individual form element in the form template, where I can define my own HTML structure?

Eg:
from--project.html.twig some things like this, and able to add individual form elements in the form template.

<form{{ attributes }}>
 {{ form.title }}
 {{ form.field_project_description }}
</form>

Thanks for any help.

I usually use something like this for template form suggestions : (works for all forms, not only entity forms)

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function <HOOK>_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  if (isset($variables['element']['#theme']) && is_array($variables['element']['#theme'])) {
    foreach ($variables['element']['#theme'] as $theme) {
      if (strpos($theme, '_edit_') !== FALSE) {
        $suggestions[] = 'form__' . str_replace('_edit_', '_', $theme);
      }
      $suggestions[] = 'form__' . $theme;
    }
  }
}


Remove language prefix from files URL I have a drupal installation in a sub folder (demos/drupal) and it supports two languages (english -default- & arabic). I imported the drupal content from an old site. My problem is that the language prefix (i.e. en or ar) is added to the url of all images and this causes the images to not appear. for example: http://www.mysite.com/demos/drupal/en/sites/default/files/image.png).

Can I remove the 'en' and direct all urls to "sites/default/files..etc" using htaccess rules?

I can't modify the content and find/replace the urls  in the database so I'm looking for a solution to avoid that.

Appreciate your help.

If you want to use mod_rewrite, here's what to put in .htaccess:

RewriteEngine on
RewriteRule ^en/(.*)$ /$1

Btw. this has little to do with Drupal, it is either an Apache thing or a DB thing (depending on how you decide to solve it).


Programmatically querying via SearchApiAcquiaSearchService I am working on a site where querying using SearchApiSolrService is successful. However, when I deploy to Acquia Cloud and attempt to access the Acquia Search using the SearchApiAcquiaSearchService I get a 403 Forbidden.

Response

SearchApiException: "403" Status: Forbidden: Forbidden in SearchApiSolrConnection->checkResponse() (line 544 of ...sites/all/modules/contrib/search_api_solr/includes/solr_connection.inc).

The subscription information is correct (via Acquia Agent). Here's a piece of the code:

Code Sample

$server = search_api_server_load('my_acquia_solr_server');
$index = search_api_index_load('my_base_index');
$query = new SearchApiQuery($index);
$query = ... lots of random filters here that work for SearchApiSolrService calls so ignoring ...
$solr = new SearchApiAcquiaSearchService($server);
$result = $solr->search($query);

Thoughts?

Note: If you were to replace the SearchApiAcquiaSearchService with the regular SearchApiSolrService, the non-Acquia versions of the site integrate with Solr perfectly fine.

The solution to this (also updated on the Drupal.org node commented above) is:

To skip this part:

$solr = new SearchApiAcquiaSearchService($server);
$result = $solr->search($query);

And simply do:

$result = $query->execute();


Encode Forward Slash with &#x2F in Text area drupal 7 form I am facing issue in Encoding forward slash with &#x2F in my custom drupal 7 form.
I have a text area field with name "Address", i am using check_plain for encode special characters, All HTML related tags are getting encoded, but i want to encode forward slash(/) as well.

Any suggestions?

You can use something like the following to convert all characters you want to convert into their corresponding HTML entity version. I have added a check on converting only non alpha-numeric characters into HTML entities. You can add a different logic to convert only those characters you want to convert (in the if condition with ctype_alum)

The following is adapted from the answer here

function encode($str) {
  $str = mb_convert_encoding($str , 'UTF-32', 'UTF-8'); //big endian
  $split = str_split($str, 4);

  $res = "";
  $pos = 0;
  foreach ($split as $c) {
    // Check if the character is alpha numeric and
    // if not, convert to HTML entity.
    if (!ctype_alnum ($str[$pos])) {
      $cur = 0;
      for ($i = 0; $i < 4; $i++) {
        $cur |= ord($c[$i]) << (8*(3 - $i));
      }
      $res .= "&#" . $cur . ";";
    }
    else {
      $res .= $str[$pos];
    }
    $pos++;
  }
  return $res;
}


Relationship between node_access gid, roles and workflow If using workflow, what database table.field does the node_access.gid map to? Does it represent a role, does it represent a workflow sid (state id), or something else?

Example:

+---------+------+-----------------+------------+--------------+--------------+
| nid     | gid  | realm           | grant_view | grant_update | grant_delete |
+---------+------+-----------------+------------+--------------+--------------+
| 1234561 |    4 | workflow_access |          1 |            1 |            1 |
| 1234562 |    5 | workflow_access |          1 |            1 |            1 |
| 1234563 |    6 | workflow_access |          1 |            1 |            1 |
| 1234564 |    7 | workflow_access |          1 |            0 |            0 |
+---------+------+-----------------+------------+--------------+--------------+

EDIT: After @Berdir's excellent response I wrote the query below to analyze the relationship between node_access.gid, workflow_access.rid, and role.rid:

# Establish relationship between workflow, roles, gids, etc.
SELECT
    r.name AS role,
    r.rid AS w_role_rid,
    wa.rid AS and_workflow_access_rid,
    ws.state AS has_access_to_state,
    wa.sid AS with_state_sid,
    IF(ws.status=1,'YES','NO') AS which_is_enabled,
    wa.grant_view, wa.grant_update, wa.grant_delete
FROM workflow_access wa
    LEFT JOIN role r ON wa.rid = r.rid
    LEFT JOIN workflow_states ws ON wa.sid = ws.sid
ORDER BY r.rid, wa.sid

If anyone notices any incongruousness with my query please comment so.

Looking at the source (the function workflow_access_node_access_records()), it looks to be the rid, which is the role id. Additionally, it is also defined in workflow_access_node_grants(), which returns the gid's for a given user. And that is the role id's for 'workflow_access' and the user id for 'workflow_access_owner'.

There is also a {workflow_access} table, that contains information about which role has which permissions for each workflow state. Based on that, the access grants for each node are then built.


Add callback to existing migrate field mapping I have a use case where I want to use the callbacks functionality for the body field in a D6->D7 migration using migrate and migrate_d2d modules. However, according to the above-referenced docs page, this is done when you are adding a new field mapping:

$this->addFieldMapping('destination_field', 'source_field')->callbacks('my_callback');

not adding to an existing mapping. How can I add a callback to an existing mapping? Do I have to remove and then re-add the mapping, or is there another way?

With some debugging and looking at code, it turned out to be pretty easy. All of the mappings are MigrateFieldMapping objects in $this->codedFieldMappings, so it's just a matter of getting a reference to that object and calling the callbacks() method. For example, to add a callback to the body field, you would use:

$this->codedFieldMappings['body']->callbacks('my_callback');


Hook_form_FORM_ID_alter problems with custom validating I have created a custom module for altering the user_register_form and with custom validating I have an error:
Notice: Undefined index: values in custom_register_validate_password() (line 17

This is the 17 line:

if (in_array($form['values']['pass'], $badpasswords)) {

I cannot understand what I'm doing wrong. Here's the full code:

<?php

    /*
     * Implements hook_form_FORM_ID_alter().
     */
    function custom_register_form_user_register_form_alter(&$form, &$form_state, $form_id) {

        $form['#validate'][] = 'custom_register_validate_password';
        //krumo($form);
     }

     /*
      * Custom password validation
      */
    function custom_register_validate_password($form, &$form_state) {
        $badpasswords = array('pass','password');
        if (in_array($form['values']['pass'], $badpasswords)) {
            form_set_error('pass', t('Please use a more secure password!'));
        }
        krumo($form_state);
    }

I think you need to write

    if (in_array($form_state['values']['pass'], $badpasswords)) {
        form_set_error('pass', t('Please use a more secure password!'));
    }

$form_state['values']['pass'] instead of $form['values']['pass']


How to add CSS class to password-strength and password-confirm on /user/register page? I want to add a class to password-strength and password-confirm on /user/register page? I tried to alter the form but as these are made with js I could not change or add anything to them.
How can I alter these?

Trying to explain, first you need to implement hook_theme(), in this case, you have to implement the function in your template.php file, that is located in the folder that contains the theme you are using (sites/all/themes/your_theme_folder).

function yourThemeName_theme()
{
$items = array();
$items['user_register_form'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('theme', 'yourTheme') . '/templates',
        'template' => 'user-register',
);
return $items;
}

After implementing the function, you have to create the template file, in the example, the template file is called user-register.tpl.php and it's located inside the "yourThemeFolder/template" folder.

In the user-register.tpl.php file you define your custom html, for the form, the code that will be rendered inside the <form></form>.
I can't test this now, but if I'm not wrong you can use the debug function to output the form array and check the fields names of your form.

debug($form);

Your template file would look like this:

<fieldset class="form-wrapper" id="edit-account">
        <legend><?php print t('User Account'); ?></legend>

                <?php
                // print render($form['account']);
                print render($form['account']['name']);
                print render($form['account']['mail']);

                ?>

                <?php
                print render($form['account']['pass']);
                print render($form['account']['pass2']);
                ?>

    </fieldset>

For a more detailed example, check the following link:
https://www.drupal.org/node/350634


How to create a membership using rules, using membership entity module I'm using the membership entity module, and the membership entity commerce module.

I am trying to create a membership using  rules, without success yet.

There is one membership action available..to activate the membership but thats all.

EDIT:
This is the rule I used for checking out a membership:

    { "rules_at_listing_import_create_user_and_membership" : {
    "LABEL" : "At listing import create user and membership",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [
      "rules",
      "commerce_cart",
      "commerce_checkout",
      "membership_entity_commerce",
      "feeds"
    ],
    "ON" : { "feeds_import_listing_import" : [] },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "user",
            "param_name" : "[node:field-first-name][node:field-last-name]",
            "param_mail" : [ "node:field-user-email" ]
          },
          "PROVIDE" : { "entity_created" : { "user_created" : "Created user" } }
        }
      },
      { "user_unblock" : { "account" : [ "user-created" ] } },
      { "entity_save" : { "data" : [ "user-created" ], "immediate" : "1" } },
      { "commerce_cart_product_add_by_sku" : {
          "USING" : {
            "user" : [ "user-created" ],
            "sku" : "Listingmember-1y",
            "quantity" : "1",
            "combine" : "1"
          },
          "PROVIDE" : { "product_add_line_item" : { "product_add_line_item" : "Added product line item" } }
        }
      },
      { "commerce_checkout_complete" : { "commerce_order" : [ "product-add-line-item:order" ] } },
      { "membership_entity_commerce_activate_term" : { "commerce_order" : [ "product-add-line-item:order" ] } }
    ]
  }
}

Using this rule, I assume that the membership is created automatically because of the membership product being checked out.

Alternatively, I tried the method without using the membership product, by straight away creating an entity of type membership using rules. That does not work, the membership is not created.

I did a good comparison of the Commerce membership entity module and the Commerce Licenses module, and the commerce licences can do te same, and has a lot more extra features, is more flexible. So switching to that module was my solution.


Review the css and theme also like we do for code using code review module To check my code in custom module we use Code Review module.   Is there a similar module for themes and CSS?

If by the 'Code Review module' you mean the Coder module, it already supports reviewing the code in themes.

  Beginning with the 5.x-2.x version, this module adds a new UI, core
  support, theme support, and a cache for faster display of unchanged
  files. It also supports rule #severity levels of "minor", "normal",
  and "critical."


How do I assign a region to programmatically created block? Hi after following this guide I was able to create multiple blocks.
But I have couple of issues.

Blocks are not created instantly need to clear cache but cant find a way to do it instantly (solution might be clearing block cache but how ?).
I need to assign region to the block while creating itself but cant do so .
I want to have x content for x block id and y content for y block id cant write a filter condition as I cant get block id of the blocks.

Basically I want to achieve all the D7 module's functionality in D8.

If anyone have an idea please help me.

That's expected. You can do it from code if needed. The following are the steps to follow.

Settings definition is done as in block.block.test_block.yml. Place that file, after editing it, in my_module/config/install and you're set. A quick hack is managing the block settings manually in a local environment and export them from /admin/config/development/configuration/single/export.

Import your settings, which can be done using code similar to the following one.
use Drupal\Core\Config\FileStorage;

$config_path = drupal_get_path('module', 'my_module') . '/config/install';
$source = new FileStorage($config_path);
$config_storage = \Drupal::service('config.storage');
$block_config = 'block.block.test_block';
$config_storage->write($block_config , $source->read($block_config));

Block settings are theme dependent.

For dynamic allocation of blocks, you can load and alter the block entity like this.
use Drupal\block\Entity\Block;

$block = Block::load('test_block');
$block->setRegion('my_region');
$block->save();


Ho to improve Drupal site score on PageSpeed Insights Site I have check score on PageSpeed Insights,
But I am getting following error

Should Fix:
Eliminate render-blocking JavaScript and CSS in above-the-fold content
Your page has 16 blocking script resources and 8 blocking CSS resources. This causes a delay in rendering your page.
None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.

A possible starting point might be the Advanced CSS/JS Aggregation module.

The following article shows some possible configuration options that can increase your PageSpeed Insights score:

https://www.northstudio.com/blog/increase-your-drupal-site-pagespeed-score-part-2-advagg


Use a contextual filter value in a view referencing a node name/path rather than id I would like to create a views that has a contextual filter with a node reference.

I'm able to view the contextual filter working when I use the node's id value, but I need to be able to use the alias or name value of that content type. I have people categorized by office (the office is also a content type because it has much more content than a taxonomy would allow). Then using the office location as a contextual filter I'm trying to show the "team" listed for each office.

/office/atlanta/team rather than /office/6/team

I'm not sure, but it could be something like

  [term:vocabulary]/[term:name]


Render field by name in custom content node template I'm trying to create a custom node template in drupal 8.

I've added the content type and am displaying them in the Front Page view.

I would like to render each field in the in the the node template (node--content-type.html.twig).

Using the recommended {{ content.field_name }} syntax, causes the node to print nothing except the title.

Are there any prerequisites to using this syntax, what am I missing here?

Ended up installing a fresh copy of Drupal and re-adding the content type (through the UI as before). After that it worked fine.

Not sure why that happened, no time to debug, will just continue with this install.

I suspect either I broke the the 'Frontpage' view while fiddling, or one of the Modules was breaking it, perhaps Twig Field Value.

I need to now access a multi value field in Twig, thinking something like {{ content.field_name.0 }}. I need to access the array directly without the use of a foreach loop, because they fit into different parts of the html layout.

Thanks for the responses!


How to check Commerce product type of current line item in Rules? When building a Drupal Commerce rule, I would like to loop over all line items and determine the product type for each line item. I would like to use the product type in a Rules Component to check whether the product is a certain type.

How can I check the line item product type when looping over line items in a Drupal Commerce shopping cart?

If the data about a product are not available when processing a "line item", you can make them available. To do so, use a technique similar to what is explained in my answer to "How to access commerce_product field of line-items using Rules to flag the Commerce Product?", which includes a Rules Component that looks like so:

{ "rules_perform_an_action_on_a_selected_line_item" : {
    "LABEL" : "Perform an action on a selected line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "commerce_product",
            "id" : [ "selected-line-item:commerce-product:product-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about this product: Product ID = [product-fetched:product-id], Product SKU = [product-fetched:sku], Product Title = [product-fetched:title], Product Creator = [product-fetched:creator]" } }
    ]
  }
}

Here is a blueprint of what you need to do:

Create a Rules Component, similar to the above Rules Component. Just an import of that Rules Component should be enough (to get started and further improve it as detailed below).
Rework the Drupal Message shown via the last Rules Action in the Rules Component (Starting with "Some details about this product"), e.g. by also using either of these available tokens that seem to be what you're interested in:

[product-fetched:type] - The machine name of the product type.
[product-fetched:type-name] - The human readable name of the product type.

Execute that Rules Component inside your Rules Loop of the rule in which you want to loop over all line items.
Improve the Rules Component from Step 1 by creating whatever additional Rules Action(s) you need. Make sure to place these Rules Action(s) AFTER that Rules Action (in the Rules Component) that performs "Fetch entity by ID".

PS: I assume this question is about D7.


How to make user's access to nodes depend on the year a node relates to? User profile is organizer of this year boat show. After registering, user can create basic pages with main photo and basic text. Afterwards, user is given another role through rules, so he can not by accident create more basic pages but can still setup images, dates, videos, announcements, which are all visible as different views contextual blocks on basic page of the user.

All is fine, except i have no idea how to setup same thing for next year? User can edit basic page, but i would rather leave past year (basic page with views blocks) somehow be archived and visible on the website and his profile, and give him option to setup data for next year.

Option 1 - Add a field to reflect the year

If you'd add a (select list) field to indicate the year that the basic page relate to, you could use the value of that field with some Rules conditions to perform all sorts of validations to prevent a user creating and/or updating pages for any years you do not want to allow.

The Rules Event would probably be "Before saving content". And the Rules Conditions would simply be (a) "Entity has field" (for this extra field) and (b) "data comparison" (to find out which year the basic page is about).

Option 2 - Use the Group module

You could use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

So to answer this question, you'd create a group for each year. For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

Resources:

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".

PS: Group is available as of D7, and has a D8 version also.


How to alter text filters conditionally based on content type? How can I get the content type of the current node from within a text filter, so I can use it to conditionally alter how the filter is applied?

Getting the node ID from the arg() function and using it to load a node object does not work because the text filter is run multiple (30+) times and exhausts the available memory.

$node = menu_get_object();
if ( !empty($node) ) {
  dd('Have a node, do something');
}

The same is true with the following method of getting the content type: $node = menu_get_object();

You could go with the following code inside your filter's callback function:

if(arg(0) == 'node' && arg(1) > 0){
  $result = db_select('node', 'n')
  ->fields('n', array('type'))
  ->condition('nid', arg(1),'=')
  ->execute()
  ->fetchAssoc();
  dsm($result['type']);
}

Good luck!


What happens to a node/menu item once it's been deleted? Once a node or menu item etc has been deleted, is there a way to restore it? Other than restoring the database?

When you delete a node or a menu item you cannot restore it unless reverting the DB.

You can use revisions and published status in order to emulate the node deletion or you can try modules like Recover.


Use contextual filter on no results behavior I'm creating a view where I'd like to use the node ID of the current node seen on the page on the no results behavior. Is it possible?

If you have the PHP input format enabled you can use arg(1) in the empty text for the view.


Hide comments on a node type for standard users I'm using the 'comment permissions' module to restrict standard 'authenticated' users from commenting on a particular node type. However I do not want them to bee able to see comments on that node either.

I want to use the commenting system as tool for discussing posts internally. So admins can discuss posts by standard users. I DO want standard users to be able to comment on some other node types.

Obviously it is very important that the author never sees these comments. 'Comment permissions' doesn't have a way to handle this part so I have overridden the node.tpl.php file and only show comments if a certain role is present (see below)

My question is; how bullet proof is this method? Can anyone suggest a better way to achieve this? Obviously a change in theme would reveal comments but are there other issues I'm not thinking of?

<?php if ( (in_array('staff', $user->roles)) || (in_array('administrator', $user->roles)) ){ ?>

// show comments

<?php } ?>

You could make a module that uses hook_comment_load() to do that user role check.

https://api.drupal.org/api/drupal/modules%21comment%21comment.api.php/function/hook_comment_load/7


Workbench moderation state tab not displayed My "Authenticated User" can not see the tab "Publishing options" on the node/add/[content type] page. What I need in my workflow is the user to select the moderation state (Draft/Moderation) the node should be in, but he can't see the tab.

I have 3 moderation states: Draft, In Moderation, Published.

The user has the following permissions:

Node:
    View published content
    View own unpublished content
    View content revisions
    create [content type] content
    edit own [content type] content
    edit any [content type] content
Workbench Moderation:
    View the moderation messages on a node
    Use "My Drafts" workbench tab
    View all unpublished content
    View moderation history

I configured the permissions looking at https://www.drupal.org/node/1175592 and https://www.youtube.com/watch?v=8nqWLrxH_4M + https://www.youtube.com/watch?v=qHYWOohhKZE

I don't know if there are other permissions that I forgot. I have already rebuilt the permissions on /admin/reports/status/rebuild, no difference.

Funny thing is that, if I assign all permissions

Moderate all content from Draft to in Moderation
Moderate all content from in Moderation to Draft
Moderate all content from in Moderation to Published

to the anonymous user, he still can't see this tab.

Any help welcome.

Ah. Again, Fooled myself - it was a simple shoot into my own foot.
I had written custom PHP code in my costom theme in the function THEME_form_alter() to suppress the whole revisoning tab:

$form['revision_information']['#access'] = FALSE;

When I then installed and configured the workbench module I didn't realize that it needs exactly THIS tab.

Works as expected now. Sorry for using your time... But maybe someone else learns from my errors...
Thanks for  your thoughts.


How do I print an individual field in block.html.twig? I have tried as many options as I can imagine but none of them prints anything except:

{{ content }}

However, I require individual fields for more control over theming.

I am using a custom block type and the following function.

function THEME_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  // Block suggestions for custom block bundles.
    if (isset($variables['elements']['content']['#block_content'])) {
    array_splice($suggestions, 1, 0, 'block__bundle__' . $variables['elements']['content']['#block_content']->bundle());
  }
}

The template is working fine. I can hard code some random text and it is displayed. I just can't display the field values.

How do I print an individual field in block.html.twig?

If you have a field called field_test you schould be able to do like this

{{ content.field_test }}

and if you want to only print the value you can do like:

{{ content.field_test[0] }}

If you want to see what is inside the field you can do like this:

{{ kint(content.field_test) }}

But only if you have Devel module installed and have Devel Kint enabled you should be able to do that.

Hope this helps :)


Use profile2 fields in custom form I'm trying to add profile2 fields in my custom form. I have created a path in my custom module in hook_menu() and in page arguments inside array, I have passed my custom_form.

In my custom_form I have returned the following code:

function custom_form($form, &$form_state) {

    global $user;
    module_load_include('inc', 'user', 'user.pages');
    return drupal_get_form('user_profile_form', $user);
}

When I go to the path I do not see the fields which I had created for a particular profile type through manage fields. Instead it renders the default user-profile-form fields.

Where I'm going wrong? Please suggest any ideas.

Thanks In advance

Solved it with the following code:

function custom_form($form, &$form_state) {

global $user;

if (!isset($form_state['profiles'])) {

  $profile = profile2_load_by_user($user, 'profile_machine_name');
  if (!$profile)
  {
    $profile = profile_create(array(
      'type' => 'profile_machine_name',
      'uid' => $user->uid
    ));
  }
  $form_state['profiles'][$profile->type] = $profile;
}

profile2_attach_form($form, &$form_state);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Save'),
);
return $form;
}


Call to undefined function After creating the node (from a default and custom node) I received the following error,

Fatal error: Call to undefined function creative_customize_comment_form()
  in /home/MYSITE/public_html/includes/form.inc on line 1865

this happens for all users even admin.

I'm assuming creative_customize_comment_form() is a custom form function, so it probably exists in either:

A file inside a module that's not enabled, so Drupal can't find it
An include file in the module that's not automagically included during the page build.

The solution to the first is obviously to enable the module.

The solution to the second is to Make sure the appropriate file is included in the page build, using module_load_include(), e.g.

module_load_include('inc', 'creative_customize', 'creative_customize.pages');
// Now call drupal_get_form()...

Without more information I can't think of any other reason (other than the function name itself being incorrect) that drupal_get_form() would fail.

Source: https://api.drupal.org/api/drupal/includes!module.inc/function/module_load_include/7


How to discover the currently active twig template I need to find out the currently active Twig template from within my module preprocess function.

function mymodule_preprocess_field(&$variables, $hook) {
    // How do i retrieve the currently active Twig template?
}

I need to know whether it is field.html.twig, field--field-example.html.twig or some other template suggestion.

Is that possible?

With the help of Clive's comment, I managed to identify the active theme suggestion.  Code below.

function mymodule_preprocess_field(&$variables, $hook) {
  $theme_suggestions = mymodule_get_theme_suggestions($hook, $variables);

  $active_suggestion = mymodule_get_active_theme_suggestion($theme_suggestions);
}

function mymodule_get_theme_suggestions(String $base_hook, array $variables) {
  // Invoke hook_theme_suggestions_HOOK().
  $suggestions = \Drupal::moduleHandler()->invokeAll('theme_suggestions_' . $base_hook, [$variables]);

  // Invoke hook_theme_suggestions_alter().
  $hooks = [
    'theme_suggestions',
    'theme_suggestions_' . $base_hook,
  ];
  \Drupal::moduleHandler()->alter($hooks, $suggestions, $variables, $base_hook);

  array_unshift($suggestions, $base_hook);

  return $suggestions;
}

function mymodule_get_active_theme_suggestion($suggestions) {

  $theme_registry = theme_get_registry(FALSE);

  // Order by most specific first.
  $suggestions = array_reverse($suggestions);

  foreach ($suggestions as $candidate) {
    if ($theme_registry
      ->has($candidate)) {
      return $candidate;
    }
  }
}


Reduce the amount of information returned from standard service actions I have a Drupal 7 Services that my frontend call when I want to get (for example) all comments of node XYZ. All works, but I want to reduce informations that this call return (yes, from the backend). For example "hostname, mail, changed, registered_name, signature" are all data that I don't want to return back. Other example: if I call "user/X" service path it return "password, mail" and other informations that I consider private.

So, how can I intercept and remove this data before that service module send it back to the caller?

For user objects specifically there's hook_services_account_object_alter(), e.g.

function MYMODULE_services_account_object_alter($account) {
  unset($account->mail);
}

For other entity/resource types there's hook_services_request_postprocess_alter(), e.g.

function MYMODULE_services_request_postprocess_alter($controller, $args, &$result) {
  // Manipulate $result till your heart's content.
}


Function to get all the user permissions Is there a Drupal 7 function that lists all the user permissions defined from enabled modules?

What I need for a module I am implementing is getting all the permissions and adding to each one a checkbox list.

Is it possible to make the value of the checkbox the same shown in the "permission" column of the "role_permission" table?

There is a Drupal function for that, user_permission_get_modules(), which returns an associative array, whose keys are the permissions and values are the modules that define those permissions.

If you only need the permissions without the module names, you can use array_keys:

$permissions = user_permission_get_modules();
$permissions = array_keys($permissions);


Toggle CCK field visibility with CCK radio buttons I have a content type with three cck fields

1 radio button, 1 text field, and 1 integer field.

What I am trying to do is by default have the text field and integer field hidden, and only show them dependent on the state of the radio button.

Example:

Two radio buttons, one which says text and one which says integer.  When the text radio box is checked, then the text box shows and the integer box is hidden and vice versa.

There is a contrib module written for just this: Conditional Fields. Here is a quote about it (from the module's project page):

... allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.


Option for auto Masspay in ubercart marketplace Is there any auto Masspay option in ubercart marketplace module. Now working with manual payment method.

Automatic mass payment (with paypal only)

Explanation:
When a user makes an order and pays with PayPal or does ExpressCheckout with PayPal and the system redirects him to "checkout/complete" the added code starts to work and makes masspay for all the orders done before that one. (Newest order not included)

Another Method :

Go to Test Accounts, select "Create Account: Preconfigured", Choose
account type "Seller", use given data
Go to API Credentials, copy API Username, Password, and Signature to
Drupal Enable uc_paypal module
Setup PayPal Website Payment Pro settings at: "Store Administration

    Configuration >> Payment Settings >> Edit >> Payment Gateways" or directly via /admin/store/settings/payment/edit/gateways

Enable this payment gateway for use API server: Sandbox
Now enter your API credentials
If IPN is setup you may now make payments at "Store administration >>
reports >> Seller reports"


Panels page or Panels node - which to use? I have two content types for a theatre listings site:

Production: title, description, image gallery, video
Show: date, ticket cost, production (nodereference to Production)

So a single Production node that runs for 14 nights will have 14 Show nodes linked to it. Simple.

Each Production page will pull together a list of Shows (using a View), images, video and maybe some other stuff. So I think Panels would be useful for this display.

But I'm struggling to understand whether it's best to create a single Panels page for this (that maybe overrides the default display of Production content type) or turn Production into a Panels node. The layout will be the same for each Production, so maybe a single Panels page is best?

The Production node edit page has to be simple and easy to edit, so making it a Panels node might add complexity?

Essentially, this boils down to what are the main differences between Panels page and Panels node?

"Essentially, this boils down to what are the main differences between Panels page and Panels node?"

A Panel page takes over the layout of the entire page. It can override one or more full pages.

A Panel node takes over one or more node(s) layout.


Article voting with feedback option I am attempting to setup an article voting system with the ability to provide feedback to the author. Only admins will be able to see feedback so I do not want it like a review attached at the bottom of each article. My idea was to create a view that only admins had permission to see. Include in this view would be the article name, rating, and feedback if any was submitted. I would like to be able to group the feedback/ratings by article instead of by entry or user and provide an overall calculated rating for the article.

It looks like fivestar is able to do some of this however I do not believe the advanced instructions:"Configuration as a CCK field / Advanced Rating" are for drupal 7. I have created a content type of "Article Feedback" and attempted to follow this answer of how to set something similar up however I do not see anywhere when I create the rating field a "voting target". I do not really understand how Node Reference works and how it will work with the desired result I stated at the beginning of this question.

I am open to using different modules and writing my own PHP script to accomplish this task. Any direction on how to accomplish this is much appreciated.

I ended up using the built in drupal comment system as the feedback and just hid the comments from everyone but admins. I used fivestar for the star rating system attached to comments.