texts:
I'm developing a site using Drupal 8.2 and I have to create a page where the user can see which nodes he or she has viewed in the last 30 days. The goal is to provide a per user "browsing history" view with the recently read content ordered by date (ideally filtered by content type).
I've checked other similar questions about this topic and I've found the following suggested modules:

Message module: Storing a per user history of interactions?
Recently read module (and others): How to log the history of nodes viewed by a user, and report about them?

Unfortunately these modules don't have Drupal 8 releases at the time of writing this question (except the Message module which has a pre-release/alpha version).
I've also reviewed the official docs and found there's a core History module that tracks which nodes have been viewed by each user and when. I have this module enabled (it was enabled by default) and I've checked that it's actually collecting user interactions in the history table. According to the docs:

In Drupal 8 and later, the History module is included in Drupal core. When enabled, the History module records which user has read which content.
This only applies to authenticated users. Entities older than 1 month will always be shown as "read".
There is no UI provided, but history data is exposed to the Views module. You can add history data as a field to show "new" or "updated" node marks. You can also use a filter to only show content that is new or updated.

this module provides some kind of interaction with Views, so I assume it should be posible to create a view to show a list with links to each node viewed by the user. I've reviewed all the options in Views (filters, contextual filters and so on) and haven't found anything related to this history.
Is it really posible to create such a view? Any pointers on how to do that? Is there any other way to do this? How would you implement this funcionality in Drupal 8?
Cheers.


texts: Best way to backup and restore the databases of a Drupal 7 multisite using Drush?

texts:
I'm looking for an easy way to backup (and if needed restore) the databases of a Drupal multisite using Drush.

Drush command I use to backup all the databases:

drush @sites sql-dump --result-file --gzip

The backup of the databases seems to work. After executing the above command, databases are automatically stored in /root/drush-backups/DATABASENAME/TIMESTAMP/DATABASENAME_TIMESTAMP.sql.gz

What command can I use to restore the last backup of the databases automatically?

What is the best way to backup and restore the databases of a Drupal 7 multisite using Drush?

PS: I'm using Git, so I only need to backup databases.

Many thanks for your advice!


texts:
I'm in the process of porting my modules from D7 to D8. No real problems so far, but...

I have a multistep form from where I need to redirect to /node/add/xyz in the last step. (All required input form data is stored in D8 TempStore before the redirect).
In d7 I used the simple and functional drupal_goto('node/add/xyz') function which is gone in D8 for whatever reason.

I looked into core modules to see how it is done in the D8 way and it seems RedirectResponse() from the Symfony routing system is the way to go. However doing something like this:

return new RedirectResponse(url('node/add/xyz', array('absolute' => TRUE)));

But this is silently ignored, no error, nothing. I read that doing RedirectResponse from somewhere in the code may not work. So my next idea of doing it was to use a form redirect in this way:

$form_state['redirect_route'] = array(
  'route_name' => 'node.add',
  'route_parameters' => array(
    'node_type' => 'xyz',
  ),
);

even without any effect. I'm out of ideas and wish drupal_goto() back. Hopefully someone out there can help me out!

Thanks in advance
bzrudi


texts: Complex newsletter with external subscribers and custom attachments

texts:
I've created a Drupal 7 site for a financial company with approx. 60 employees. Only the employees are registered users.

The company has about 3000 customers that are registered in an external accounting system, with financial data for each customer. I have access to all customer data through soap 1.2 web services.

I have written a couple of custom modules that handles customer login, so that each customer can have access to an up to date report on their finacial status. I validate the login through a web service, and display their financial data also pulled from another web service to the accounting system. They can download the report as a PDF that is dynamically generated.

The company now wants to send a monthly report to each customer in email with the customers report attached as a PDF file. They have become quite comfortable with the drupal 7 admin interface and want to control when to send, see how many failed emails - essentially everything simplenews does.

Has anyone done anything similar? Only the admin interface is drupal based - I will need to provide the "subscribers" list and somehow link the "subscriber" with his/her correct PDF report. Also, customers come and go, so the subscriber list is ever changing.

I guess I could create a totally custom module solution, but I really would like to use existing email handling, etc from an existing newsletter module.

Any tips or advice would be greatly appreciated.

Thanks, in advance!


texts: Field template for display mode of referenced paragraph

texts:
I have a custom field field_platform (referencing a the custom paragraph type platform) and a template for my field: field--field-platform.html.twig. Is there a way to override this for a specific display mode of the referenced paragraph type? I have a mode named cover_view for the custom paragraph type platform I want to override the field template for.

I found Field template for display mode but the template suggestion is for the display mode of the content, not the referenced paragraph.

Drupal 8.5.6, Paragraphs 8.x-1.3

Thanks in advance!


texts: Code to take quiz again on the next day after user is failed

texts:
In drupal 6, I had a requirement to enable the users to take the quiz on the next day if they failed and from somewhere I got the following code to make that work. They added one more variables, time_end and used strtotime('today')

But now I upgraded to Drupal 7 and code for the same a little bit changed and I couldn't make that work. I am looking forward to getting help to achieve it. I am using quiz quiz-7.x-4.0-rc1

Drupal 6 Original lines

// Check to see if this user is allowed to take the quiz again:
  if ($quiz->takes > 0) {
//   $query = "SELECT COUNT(*) AS takes FROM {quiz_node_results} WHERE uid = %d AND nid = %d";
//   $taken = db_result(db_query($query, $user->uid, $quiz->nid));

Drupal 6 Changed lines (only first two lines. after that code remains the same except drupal_set_message.)

     $query = "SELECT COUNT(*) AS takes FROM {quiz_node_results} WHERE uid = %d AND nid = %d AND time_end > %d";
        $taken = db_result(db_query($query, $user->uid, $quiz->nid, strtotime('today')));

    $allowed_times = format_plural($quiz->takes, '1 time', '@count times');
    $taken_times   = format_plural($taken, '1 time', '@count times');

Drupal 7 Original lines.

  // Check to see if this user is allowed to take the quiz again:
  if ($quiz->takes > 0) {
    $taken = db_query("SELECT COUNT(*) AS takes FROM {quiz_node_results} WHERE uid = :uid AND nid = :nid", array(':uid' => $user->uid, ':nid' => $quiz->nid))->fetchField();
    $allowed_times = format_plural($quiz->takes, '1 time', '@count times');
    $taken_times   = format_plural($taken, '1 time', '@count times');

Full drupal 7 code is available here DrupalContrib


texts:
I moved a site from a hosted server to my local machine and none of the links that point to internal pages work even though they look correct. I'm getting odd behaviour as described below. This is true even for the admin toolbar provided by the module (People, Modules, Configuration, etc.)

My process was as usual, I copied all the files down, exported/dumped the database, created a local db and then imported the dump.

(I'm putting in lh instead of localhost bec stackexchange won't allow links with localhost)
I was able to login via lh/myidols5/?q=user but not lh/myidols5/user which gives 'access denied'. From lh/myidols5/?q=user, if I click on any link say the home button in the admin toolbar I go to the right page but am logged out. The address bar says lh/myidols5/ which is correct so I'm at a loss as to why I'm logged out.

Anyone know what the issue is?

Thanks


texts: In which folder should I install Composer on a shared linux server?

texts:
The "Questions that may already have your answer" do give various instructions on how to install Drush and/or Composer, but they don't address my question. I did come across this comment:

Q: drush - which folder for install on VPS / root server (newbie):
A: "You can install Drush in the folder of your choice. Preferably outside www-directory."

My question: I'm not sure if this is applicable to Composer as well?
And if it is applicable to Composer as well, why do people give specific folders into which Composer must be installed into?

The reason for my concern into which folder I install Composer is because I want to run it without problems (in any case with as little as possible).

I'm listing the different options:

mdir bin, cd bin, install Composer in [~/bin] directory.
Install in /home/username/bin
Install in [~/bin] and move to /usr/local/bin
Install in the /usr/local/bin folder
That is a hidden folder, I can access it if I say "cd /usr/local/bin" in my terminal, but it doesn't show in the file manager of cpanel. How does that relate to /home/username/bin (or doesn't it)?
Install in the public_html folder (home/username/public_html)
One article says that Drupal is installed in the /var/www/drupal folder.
Another articles says that Drupal is installed in domains/websitename.com/htdocs/www

It seems to me that the [~/bin] directory is the preferred one?


texts: How do I add files to the solr index in Drupal 6?

texts:
I'm using Drupal 6, Solr 4.9.0 and  Apache Solr module v 6.x-3.x.  I'm trying to use Solr to index files attached to nodes, but it's not working.  I'm using the Solr Attachments module but I know it's not compatible with 6.x-3.x since that uses the new Solr API of the Drupal 7 version.

Here's what I tried to do so far, and you'll have to pardon me if it looks bad because I'm new to the Solr API:

In apachesolr_attachments.module I changed apachesolr_attachments_update_index this is the code in the do while loop:

 $rows = apachesolr_index_get_entities_to_index($env_id, 'node',   $cron_limit);
 $documents = array();
   foreach($rows as $row){
     apachesolr_attachments_add_documents(&$documents, $row->entity_id, 'apachesolr_attachments');
    }
    $success = apachesolr_index_send_to_solr($env_id, $documents);

The function apachesolr_attachments_add_documents is the same, and it populates an array of "documents" that are fed to apachesolr_index_send_to_solr.

During a quick test when I killed the process quickly with a die command after the first cron batch it seemed to work, but letting it run doesn't work.  The search results don't return

If there's a better way, I'd appreciate anyone's help in pointing me to it.

Thanks


texts:
I have written my own module for example called: calc
and i have used module_load_include('inc', 'calc', 'form.inc') in my calc.module file,
and placed form.inc file inside my module's directory: calc/form.inc but it doesn't see that file. What am I doing wrong?

I am using Drupal 6.


texts: How can I substitute field in hook_query_alter?

texts:
I have a query, with a date field, let's say it is aliased as enabled. And joined table with field enabled_for_website. In my query alter, I want to substitute global enabled with date specific to website user is viewing (domain access, but it doesn't really matter here).

I tried simplistic approach:

function MYMODULE_query_MYTAG_alter($products_query) {
  $products_query->join('website_has_product', 'wp', 'p.idProduct = wp.idProduct');
  $products_query->join('website', 'w', 'wp.idWebsite = w.idWebsite');
  global $user;
  if ($user->uid == 1) {
    $products_query->addField('wp', 'website_enabled', 'enabled');
  }
  $products_query->condition('w.WebsiteName', /*where are we */, '=');
}

I'm getting expected error:

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'enabled' in order clause is ambiguous

Is there a way to remove other column? SelectQuery::$fields is protected, and I see no method to remove / substitute fields in it. I would prefer to avoid extending any classes.


texts: Like the field_get_items function, is there a function to update a field's value? I want to update a field of type user reference.


texts: How do I retrieve values using $form_state?

texts:
Possible Duplicate:
  Custom validate and submit don't works

I am using Drupal 7 $form_state['values'] to get values from all fields, but the array is empty, and when I use dsm() there is no value.

Hi, please this is maybe complex question but I really need help, I can't finish my task almost 3 days. If I need to write somewhere else you just say.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
    case 'user_profile_form':

    //only pre-render works
    $form['#pre_render'][] = 'mymodule_user_profile_form_pre_render';
//I try to empty fields with states attribute, but without success. Disabled work OK.
$form['field_company_url']['und']['0']['value']['#states'] = array(
     'empty' => array(':input[name="field_company_confidential[und]"]' => array('checked' => TRUE)),
     'disabled' => array(':input[name="field_company_confidential[und]"]' => array('checked' => TRUE)),);

         //these two don't work as expected
         $form['#validate'][] = 'mymodule_user_profile_form_validate';
         $form['#submit'][] = 'mymodule_user_profile_form_submit';

        //also try this one but nothing
        //$form['actions']['submit']['#submit'][] = 'mymodule_user_profile_form_submit';
    }
}

function mymodule_user_profile_form_submit($form, &$form_state) {
//here I want to download image from other website and set as logo
}

function mymodule_user_profile_form_validate($form, &$form_state) {
//here I need to check if checkbox is checked emty all other fields
    if ($form_state['values']['field_company_confidential'] == TRUE){
     //THEN set all other fields empty
        $form_state['values']['field_company_url']['und']['0'] = '';
    }

    return $form;
}


texts:
I know that disabled modules do not effect performance. I also know that typically the number of modules you have enabled will effect the speed of you site. One individual on Drupal.org said you should never have more than 40 modules enabled. I found this strange because I would assume some modules are more intensive than others.

Is it simply the number of modules that somehow effect performance, (because the hook is always called), or is it really dependent on what you are doing in the module?


texts: I am looking to embed flash in D7 on a simple page. How would I do this?


texts: Sanitized text input for EntityMetadataWrapper set()

texts:
Through searching, I've found plenty of examples using the EntityMetadataWrapper set() function to update entity fields, and have implemented it successfully in my module. However, I haven't been able to find much in the way of documentation / best practices on the different array options you can pass to set(). I want to make sure the way I'm updating data won't cause unforeseen issues later on.

I am doing a straightforward update of text field values in a form submit callback:

function hook_FORM_ID_submit(&$form, &$form_state) {
  // Get the node.
  $node = node_load($form_state['nid']);

  // Create entity metadata wrapper to get and set values easily.
  $node_wrapper = entity_metadata_wrapper('node', $node, array('bundle', $node->type));

  // Set fields
  $node_wrapper->field_quip->set(array("value" => $form_state['values']['field_quip']['value']));
  $node_wrapper->field_short_sentence_summary->set(array("value" => $form_state['values']['field_short_sentence_summary']['value']));

  // Save node.
  $node_wrapper->save();
}

I am passing set() an array with only one key: value. This seems to be working fine. However, I notice that when I call value() on that same field before I set a new value, it returns an array with three keys:

$original_value = $node_wrapper->field_quip->value();

// Output of $original_value:
// Array (
//   'value' => '
The original value
',
//   'format' => 'general',
//   'safe_value' => '
The original safe value
',
// )

The way I am current setting fields, I lose the sanitized value. Will this come back to bite me? Should I be running check_markup() on the value and passing format and safe_value to set(), rather than an array with just value? I might be splitting hairs here, but I want to make sure I do things right.


texts: How can I add a profile tab with the viewed users nodes?

texts:
I have tried using views and profile2 so far to create a tab in the users profile to display a list of the nodes created by that very author.
I am not trying to display all nodes of the current logged in user but of the user associated with the profile that is being viewed.

I have tried to use contextual filters of the Views module (and using a path with arguments), but the Author uid context will always refer to the logged in user rather than to the user, whose profile is being viewed. I have trying to fiddle with the Relationship option of the Views module without success.

So my first step would be to create a View which displays nodes of a user in relation to his profile page-URL (I suppose).
Second step would be to display that view as a tab in the profile overview.

I do not necessarily have to use profile2 and views. I just thought it would be the most adequate way to deal with the issue.

Thank you in advance for every help.

/edit: a similar question I have found on stackexchange earlier, but it has not been resolved it seems.


texts: How to dynamically add options to  list in CKeditor dialog

texts:
I am building a CKEditor plugin for Drupal 8. Currently it adds a toolbar button which triggers a modal dialog containing a select list with a few options. I've hardcoded the options in plugin.js, and everything works as expected. But those options must actually be dynamically added with php.

This is my plugin dialog definition, as per http://docs.ckeditor.com/#!/api/CKEDITOR.dialog.definition.select with hardcoded options.

This goes in the plugin.js file loaded via CKEditorPluginInterface::getFile() in my plugin class:

CKEDITOR.dialog.add('pluginDialog', function(editor) {
  return {
    title: 'Available options',
    minWidth: 300,
    minHeight: 200,
    resizable: CKEDITOR.DIALOG_RESIZE_BOTH,
    setup: function(e) {},
    commit: function(e) {},

    contents: [{
      id: 'tab-options',
      elements: [{
        type: 'select',
        id: 'select-options',
        label: 'Select an option:',
        items: [
          ['Option 1', 'Option 1'],
          ['Option 2', 'Option 2'],
          ['Option 3', 'Option 3'],
          ['Option 4', 'Option 4']
        ]
      }]
    }]
  };
});

CKEDITOR.dialog.definition.contents.elements.items[] have to be built from PHP. Any help is appreciated.


texts: Views Slideshow with numbered navigation disappears

texts:
So a little background on my current setup. The views slideshow having issues is on the homepage:
http://pacificwhale.org

I am running Drupal 6, and using Views slideshow 2.4 with nodequeue to feed 6 nodes that are of the photo content type. The slideshow that I am working closely with sits on the homepage of my website. Sometimes it works, sometimes it doesn't. When it stops working, the numbered navigation disappears from the page, and in the source code, I'm noticing that the jQuery.extend function call in the html page header is missing this code:

  "viewsSlideshowSingleFrame": {
  "#views_slideshow_singleframe_main_nodequeue_1-block": { "num_divs":
  6, "id_prefix": "#views_slideshow_singleframe_main_", "div_prefix":
  "#views_slideshow_singleframe_div_", "vss_id": "nodequeue_1-block",
  "timeout": 5000, "sort": 1, "effect": "fade", "speed": 700,
  "start_paused": 0, "delay": 0, "fixed_height": 1, "random": 0,
  "pause": 2, "pause_on_click": 0, "pause_when_hidden": 0,
  "pause_when_hidden_type": "full", "amount_allowed_visible": "",
  "remember_slide": 0, "remember_slide_days": 1, "controls": 0,
  "items_per_slide": 1, "pager": 2, "pager_type": "Numbered",
  "pager_hover": 1, "pager_click_to_page": 0, "image_count": 0,
  "nowrap": 0, "sync": 1, "advanced": "", "ie": { "cleartype": "true",
  "cleartypenobg": "false" } } } });

To view the html for the slideshow you can do a view source from our homepage.

To make the numbered navigation work, I must from the admin area of drupal6 perform a "flush all caches" from a page other than the homepage. After doing this, if I navigate to the homepage while logged into the admin area, the slideshow will not work, and there will be no numbered navigation. However, if I log out of the admin area and then navigate to the homepage and view the slideshow, I notice that the numbers are working and the slideshow automatically rotates through my images.

An interesting oddity, is that if I am logged into the admin area and I perform a "flush all caches" from the homepage, then the slideshow will display navigation and work inside the admin area, but if I log out of the admin area, it will not display the numbered menu, and for me or any other viewer of the website the slideshow is broken with no navigation, and the jQuery.extend function is missing the viewsSlideshowSingleFrame variable settings.

Another interesting oddity is that the slideshow navigation once fixed by flush all caches, later on it will revert back to not working, and I must go through the steps again to get it to work, and I'm in a hopeless cycle to get it to work again.

I've attached a screen capture of my views setting for nodequeue_1. You'll notice that I've turned off caching for this view/nodequeue, so I don't understand why flushing all caches makes a difference in fixing the slideshow navigation.


texts: Managing module library dependencies with composer

texts:
I've found Dependencies in a custom module with drupal-composer, How can I include a third party library in my custom module without using Composer Manager and How to manage contrib modules composer dependencies on drupal 8 which are releated to my question, but no longer seem to apply since Drupal 8.1 and the deprecation of Composer manager.

Also popular guides such as The definitive introduction to D8 and Composer appear to no longer apply as they also mention composer manager.

The other solution opposed to composer manager, alter the core composer.json file feels like too much core hacking and would probably break with every Drush update of Drupal core(?).

More specifically, I am attempting to update Views vCards from Drupal 7 to 8. I have created my composer.json file as follows:

{
  "name": "drupal/views_vcards",
  "description": "Allows creation of vCards using the fields provided by the Views module.",
  "type": "drupal-module",
  "license": "GPL-2.0+",
  "homepage": "https://drupal.org/project/views_vcards",
  "require": {
    "maennchen/zipstream-php": "0.3.*"
  }
}

But if I put a composer.json file in my module folder, how do I make Drupal aware that that file is there, and how do I make sure the required zipstream-php library is downloaded?

Simply running composer update from the Drupal root does update a lot of Drupal dependencies, but it does not include the composer.json files that are in the modules folders. I also don't assume I should be calling composer install from inside all modules with dependencies.

How do I make Drupal aware of a module's dependency without using composer manager and/or hacking core?

UPDATE:

The composer merge plugin used by core appears to have support a wildcard path:

{
    "require": {
        "wikimedia/composer-merge-plugin": "dev-master"
    },
    "extra": {
        "merge-plugin": {
            "include": [
                "composer.local.json",
                "extensions/*/composer.json" // < ---- THIS LINE
            ],
            "require": [
                "submodule/composer.json"
            ],
            "recurse": true,
            "replace": false,
            "merge-dev": true,
            "merge-extra": false
        }
    }
}

Why doesn't core merge modules/*/composer.json, that would solve everything right?

Update 2:

THe reasoning for not supporting this is covered in this issue (which also has been quiet for some time now).


texts: How to identify and target a form element?

texts:
A similar question has been asked before: How do you identify a form element?

I am using the Devel module and dpm($form) outputs the object nicely:

But I can't set/change the default value of a custom field. How do I target set the default value to 164 in this case?

$form['question_node_form']['field_points']['und']['0']['value']['#default_value'] = 164;

The above does not work and the points_field is blank.

EDIT (complete function):

function custom2_form_question_node_form_alter(&$form, &$form_state, &$form_id) {
    drupal_set_message("Form ID is : " . $form_id);
    dpm($form);
    $form['question_node_form']['field_points']['und']['0']['value']['#default_value'] = 164;
}


texts: How to force a running migration to stop

texts:
I created a migration with a query that seems to have broken my migration. I added two groupBy on a query, instead of two orderBys. As a result, running drush mi MyMigration got stuck in what appeared to be an endless loop.

I CTRL-C'd the process and then ran a drush mst --all, but now the status is reporting as "Stopping" in the UI, and the drush ms command does not return.

I tried stoping and restarting MAMP, but to no effect.

Is there someway to force my migration to get unstuck?


texts: How do I get the referring entity of a referenced node in a template file?

texts:
I am struggling since a couple of days with my problem now and I have no idea what else I can do to come to a stage of enlightenment.

In Drupal 8 I have a content type called "Release" and a content type "Article" which, among others, contains Reviews of Releases. So in Releases I created an entity reference field called "Review" which references Article content type.

For index pages I could create views of Articles and there I pretty easy could integrate the fields of the referencing release entity via the Relations section in views administration. There the reverse direction of a relationship is not a problem.

How do I access the fields of the release in a node--article.html.twig template?

Edited due to character limitation in the comments section (I hope this is allowed):
Thank you so much, @JeremyM4an, but there was a little misunderstanding due to my bad explanation of the problem. I should have mentioned that article has a reference to a taxonomy term, called field_post_category.

So a review is an article with field_post_category == 'Review' and finally a release has an entity reference field, called field_review, referring to article. After reading your answer I tried this:

$category_field = $node->get('field_post_category');
$category_field = $category_field->getValue();
if( isset($category_field[0]['target_id']) && $category_field[0]['target_id'] ){
  $term = taxonomy_term_load($category_field[0]['target_id']);
  if($term && $term->get('name')->value == 'Reviews'){
    $release = \Drupal::entityQuery('node')
    ->condition('type', 'release')
    ->condition('field_review.entity:node.nid', $node->id())
    ->execute();
    // Load release node and store in variables.
    $variables['release'] = Node::load(array_values($release)[0]);
  }
}

But this does not work.


texts: Hide language flag on this language page?

texts:
I have 2 languages on my Drupal 8 site and use Language Icons module for them:

Latin and
Celtic

I think it is not convenient to have both flags on each version. But D8 does not add language code class in body and I cannot hide flag.

Please where is solution?


texts: Can not get checkbox's to be mutually exclusive with simple form

texts:
I want 2 checkbox's that are mutually exclusive. In the example below when you click on one it will work for like one cycle then working as they will both become selected.  Is this not possible?  What is the best approach for something like this ?  #states seems so limiting, but I don't want to quite give up on FAPI.

I am starting to suspect #states is mainly just useful for collapsing/expanding fieldsets.

function form_example_stacko_form($form, &$form_state) {

$form['ourfieldset'] = array(
  '#type' => 'fieldset',
  '#title' => t('Fieldset'),
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
);
$form['ourfieldset']['checkbox1'] = array(
  '#type' => 'checkbox',
  '#states' => array(
      'unchecked' => array(
        array(':input[name="checkbox2"]' => array('checked' => TRUE)),
      ),
   ),
);
$form['ourfieldset']['checkbox2'] = array(
  '#type' => 'checkbox',
   '#states' => array(
      'unchecked' => array(
        array(':input[name="checkbox1"]' => array('checked' => TRUE)),
     ),
  ),
);

return $form;
}


texts: How to stop same-state state changes in Workflow state change block?

texts:
I am using Workflow with a custom content type. I have the Workflow state transition form as a sidebar on my node view page. I made the workflow states into buttons so that you can choose which state to transition to.

How can I remove buttons that are the same state as the node? For example: If the node is already in Draft state, the Draft button should not be shown. If it's in Declined mode, the Declined button should not be shown.


texts: Drush make, git repository checkout specific subdirectory

texts:
I've got a make file in which I want to pull in a remote Git repository and only fetch a subdirectory. I've tried as following:

projects[example_module][type] = "module"
projects[example_module][download][type] = "git"
projects[example_module][download][url] = "git@bitbucket.org:team/example_modules.git"
projects[example_module][download][subtree] = "example_module_subdir"

Though, this creates a example_module folder where I expect it to be, though it contains the entire repository. What am I overlooking? Is this impossible? (using Drush 7.0.0)


texts: I'm trying to learn about the functionality of this module, however I don't understand quite right what the Redirect to URL option means/does. Any hint in the right direction will be much appreciated.


texts: Making text fields autocomplete in views exposed filters

texts:
I want to make a text field auto complete in a views exposed form. I tried using the following code but nothing happens(I don't see that blue icon in the text field):

<?php
function nk_menu() {
    $items['nk/autocomplete'] = array(
        'page callback' => '_nk_autocomplete',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK
    );
    return $items;
}
function nk_form_alter(&$form, &$form_state, $form_id) {
    if (($form_id == 'views_exposed_form') &&  ($form['#id'] == 'views-exposed-form-my-page')) {
        $form['title']['#autocomplete_path'] = 'nk/autocomplete';
        $form['title']['#default_value'] = 'abcd'; // this one also doesn't work
        print_r($form); // to be sure that properties has been added to the form (they are added)
    }
}

function _nk_autocomplete($string) {
  // ...
}

Why doesn't it work? I know that there is a module for that, but I want to know why mine doesn't work?


texts:
How can I get file ID like I got, for instance, file URI:

$getFile = $entity->get('field_file')->entity->getFileUri();

I need it to send an email (swiftmailer)

$file_one = file_load(1);


texts: How do I populate an email field from a single user “Name” reference?

texts:
I have a content type in which I use an entity reference to reference a Name field in a user account. I am trying to populate an email field in the content type with the email of the entity referenced above. I have tried creating an entity reference view and can get it to show and save: Name, Email Address in the node. However, because of some rules I am using, I really need them to be saved to separate fields. So I tried the Entity Reference Autofill module which seems like it does exactly what I am looking for, but, it only works with existing fields, and for some reason, I can’t get the user account fields to show-up as existing fields when trying to add them to the content type.

So, is there a way for a single reference to populate more fields using the initial reference as a ‘key’?

Or…

Is there a way to get user account fields to show-up as existing fileds so I can just use the Entity Reference Autofill module?

Thanks so much.


texts: how to pass arguments in forms submit array in drupal

texts:
I would like to pass arguments from the code.

`$form['td_deals']['fetch_deals'] = array(
    '#type' => 'submit',
    '#value' => t('Fetch Deals'),
    '#weight' => 45,
    '#submit' => array('td_import_fetch'),
  );`

The submit in the form calls a function td_import_fetch, i would like to pass another argument (A variable ) in that array. is it possible?


texts: Array Field for a Content Type. Is it possible?

texts:
I'm new in drupal and I'm about to use drupal for my expanding site.
This is my issue:
I have some documents which segmented to sentences and words and each word has a tag for example:

Document:
   This is a test text to show what I say. This is the second sentence. This is the third.
Sentences:
   1. This is a test text to show what I say
   2. This is the second sentence
and so on.

Tagged words:
   This => ABC
   is => DEF
   a => EE
   test => NME
and so on.

I would like to make a node for each document not each word or sentence and store sentences and words as fields.
This data is stored in a mysql database and I can export it in any form.
How can I implement this structure in Drupal?
Is there any module for it? or I should develop a new module?
or any other solution?

Thank you all so much


texts: How to export / feature the "picture guidelines" field

texts:
I have some legal mentions to put under the file upload form of user account.

I would like to put them a feature some elements about user configuration, but I'm not able to find which variable (i.e. Strongarm or anything else) is mapped to field "Picture guidelines"
(available in Home » Administration » Configuration » People).

Could someone give me a hint, or is it even possible ?


texts: node_view does not show the comments box

texts: I am using node_view(node_load($nid), "full") and I print(render()) the result in a template. But the content of the node is appearing but not the comments nor the comments form. How can I display them ?


texts: show amount of results for exposed filter

texts:
I have a couple of exposed filters to filter the content in my view.
Most of them are taxonomy terms, now i would like to show how many nodes are tagged with that term behind the taxonomy term.

example:

London (5)
Paris (3)
Madrid (2)
...

Any idea how i can do this?


texts: Changing the html and order of system fields(pass/email/locale/etc) of user edit form

texts:
I have changed a number of forms accessible by users to fit a certain style. To do this I used an #after_build function that adds prefixes and suffixes to fields, as well as a bit of javascript. This was straightforward enough(and I hope the appropriate way to do that, though I'm not sure).

However, coming upon the user edit form, it does not behave as other forms do. The default system fields such as password, locale, email, etc, cannot be reordered and I can't seem to add prefixes or suffixes to them to insert my HTML.

I have read some things about using a template for forms via hook_theme() function, however I could not get Drupal to use my template file for the user profile edit form, though it works just fine for other forms. This was a last resort, however, and I prefer other means if possible.

How do I correctly alter the layout and html of the user profile edit form? Thank you for your time.


texts: Elysia cron and feeds being stuck - how to resume the imports?

texts:
I have a bunch of Feeds imports, programmed automatically with Elysia Cron.

There is a problem with the size of the content to be loaded, as the import uses to hang, and always at about the same approx. point in a definite feed. The feed, imported manually, throws no errors and do all its stuff perfectly, only fails in automated cron, getting stuck.

After I unblock the Feed with this

 update feeds_source set state = 'b:0;';
 update feeds_source set fetcher_result='b:0;';

And reset the Elysia table with this

 UPDATE elysia_cron SET running = 0 WHERE name = :name_of_process

sometimes the Elysia Cron starts again, but, to my dismay, no Feed process is launched even if Elysia Cron says otherwise. There is a Running indication, but no feed importation is done, and the progress indicator in the Feed itself indicates that it is not working.

What can I do, someone has the same problems? I have read tons of documentation, but I find no solution, I see terrible stories on the net about updating processes enduring for weeks, shouldn't just 4.000 products (nodes, taxonomies) load in just 5 minutes?


texts:
I am trying to show a CAPTCHA image in the form of my custom form, but it doesn't appear.

Why doesn't this code show the CAPTCHA as expected?

/**
 * Created by PhpStorm.
 * User: sony
 * Date: 28/02/2016
 * Time: 23:23
 */

/**
 * @file
 * Contains \Drupal\contact_form\Form\ContributeForm.
 */

namespace Drupal\contact_form\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\UrlHelper;

/**
 * Contribute form.
 */
class ContributeForm extends FormBase {
    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'contact_form_contribute_form';
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {
        $form['Full Name'] = array(
            '#type' => 'textfield',
            '#title' => t('Full Name'),
            '#required' => TRUE,
        );
        $form['E-mail'] = array(
            '#type' => 'email',
            '#title' => t('E-mail'),
        );

        $form['Type of feedback'] = array(
            '#type' => 'radios',
            '#title' => t('Feedback'),
            '#description' => t('Type of feedback'),
            '#options' => array(
                t('Comments or suggestions'),
                t('Questions'),
                t('Report a problem(s)'),
                t('Other'),
            )
        );
        $form['Subject'] = array(
            '#type' => 'textfield',
            '#title' => t('Subject'),
        );
        $form['Your Message'] = array(
            '#type' => 'textarea',
            '#title' => t('Your Message'),
        );
        $form['my_captcha_element'] = array(
            '#type' => 'captcha',
            '#captcha_type' => 'Image',
        );

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

    }

    /**
     * {@inheritdoc}
     */
    public function validateForm(array &$form, FormStateInterface $form_state) {
        if (!UrlHelper::isValid($form_state->getValue('video'), TRUE)) {
            $form_state->setErrorByName('video', $this->t("The video url '%url' is invalid.", array('%url' => $form_state->getValue('video'))));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        foreach ($form_state->getValues() as $key => $value) {
            drupal_set_message($key . ': ' . $value);
        }
    }


texts: Displaying Special Characters and Letters in Drupal 7 Site

texts:
I have a page that lists several non-English names which contain special letters with dots and tildas above them. Currently, those are not being displayed properly. In place of the letters the site displays question marks in a small black diamond.

How can I fix this? Is there a module? Could this be an encoding issue? Having looked at the source, I found that the page is set to UTF-8.


texts: Custom Block Config - Accepting array of objects

texts:
I have built a component following the docs but am wanting to add configure to allow the user to add a series of objects that each contain a 'title' (a text field) and a 'content' (a list of text fields) and cannot seem to find this documented anywhere. Ideally the user could select the block and then, in the configuration, add as many afore-mentioned objects to have them all be displayed wherever the block is placed.

Right now the 'hello world' demo in the docs looks like:

$form['hello_block_name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Who'),
      '#description' => $this->t('Who do you want to say hello to?'),
      '#default_value' => isset($config['hello_block_name']) ? $config['hello_block_name'] : '',
    ];

Any clarification or tips would be greatly appreciated, thanks!


texts: Displaying uid on user/x/ and user/x/edit page

texts:
I want to display the uid (read-only) of the user on both the user/x and user/x/edit page.

By using the function below I managed to show the uid on the user/x/edit page.

function my_module_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
    if (arg(0) == 'user') {
        $form['uid_read_only'] = array(
            '#markup' => 'User id : ' . '<b>' . arg(1) . '</b>',
            '#weight' => -500,
            '#disabled' => TRUE,
        );
    }
}

How do I show the uid on the user/x page (view state)?


texts: Hide blocks from the administration page according to the user role

texts:
Is there a way that certain roles can only manipulate blocks that are assigned to them?

That is, if a user with an a editor role enters to "admin/structure/block", I just want you to see and be able to manipulate the blocks that I define, the rest of the blocks must remain hidden for this user / role.

Is this possible to do?.


texts: How can users set their own price for their products?

texts:
This question is a followup question to my prior question ...

Consider authenticated users of site are "STOREs". Any store (= user) should be able to set the product's price in their profile. So that product A sells at 200$ for Store B and sells at 150$ for Store C. How can I do it? I want Stores can set their price in their profile.


texts: How to send auto login email using Email Auto Login drupal module?

texts:
I have enabled Email Auto login Module on drupal 7. How can I send an auto login email using the above module. I have enabled the module and then saved the settings from the link
http://www.example.com/admin/config/system/email_auto_login. I have even checked the README file but could not find a way to send a auto login email using token
How can I send the auto login email using this module?


texts:
I want the date for the last login for a defined role, but I have a problem with my query with drupal 7.

I have the good answer in phpmyadmin with this query :

SELECT login FROM `users` AS u, `users_roles` AS r
WHERE u.uid = r.uid
AND r.rid = 3
ORDER BY login DESC LIMIT 1

But an error with Drupal7... I tried this code :s :

$query = db_select('users','u')
 ->join('users_roles','r','r.uid = u.uid')
 ->fields('u',array('uid'))
 ->fields('r',array('rid'))
 ->condition('r.rid', '3', '=')
 ->orderBy('login', 'DESC')
 ->range(0,1);
$res = $query->execute();

Thanks

Edit : Thank for your answer Clive , this code works :

$query = db_select('users','u');
$query->join('users_roles','r','r.uid = u.uid');
$query->fields('u',array('login'))
 ->condition('r.rid', '3', '=')
 ->orderBy('login', 'ASC')
 ->range(0,1);

$res = $query->execute();
return $res->fetchField();


texts: *.module file not included, even after cache clear

texts:
I added a *.module file to a custom module, to implement some hooks.

I found that the *.module was never included, even after cache clear (via devel menu "Cache clear". Even putting a "die()" statement at the top of the file did not crash anything.

Only after drush pmu + drush en, was the *.module file included in every request.

What am I missing? Is this a bug?


texts: How to make galleries relative to particular nodes?

texts:
I have a site with news and I want to make it possible for admin to add image gallery to Articles (nodes) the admin wants. So, the idea is to make gallery image field for every content type from which images should be taken. If admin wants gallery for that article the admin can upload images, if the admin don't the admin can just leave it alone, and Drupal renders that node without gallery perfectly normal.

So, I made that gallery image field for every content type, and used Views module for taking and rendering pictures. But, whereas views taking pictures at content type level not node level, that is the reason why unpleasant consequence appear: gallery from particular node, shows on every node of that type.

My question is how to make galleries relative to particular nodes (specific gallery for specific node)? And it should be extremely easy for admin to manipulate.


texts: How can I register a image_style theme function in my module which only works in my theme's template?

texts:
Is there a way to tell drupal that my module has a theme function which usually only works in my theme?

If I write in my theme's template.php:

function mytheme_image_style($variables) {

  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );

  image_style_transform_dimensions($variables['style_name'], $dimensions);

  $variables['width'] = $dimensions['width'];
  $variables['height'] = $dimensions['height'];

  // Determine the URL for the styled image.

  $variables['path'] = image_style_url($variables['style_name'], $variables['path']);

  // do additional stuff

  return theme('image', $variables);
}

everything works fine. If I move this code to a module it does not work, though:

function mymodule_image_style($variables) {

  // code

  return theme('image', $variables);
}

How can I use the theme_image_style function/hook in my module?


texts:
I want to have "Add new comment" link to open in a new page. I already read Placing the comment form on a separate page, but this didn't solve my problem. When I go to /comment/reply/[nid] or /comment/reply/[nid]#comment-form, a page opens with "Add new comment" as the h1 page title. Then underneath the page title is my entire custom content type, followed by the comment form. I don't know why my content type is also displaying. In my content type, I've got "Show reply form on the same page as comments" unchecked. In the "Comment Fields" tab, I only have the fields I want on the comment form and no fields from my content type are listed. Can anyone offer any suggestions?

Thanks,
Paul


texts: Second product attribute resets if first product attribute is changed

texts:
I have a tshirt product on my Drupal Commerce webstore. The shirt has these options, in this order:

Size /
Color /
Sleeve Length

All shirts are available in all sizes/colors/sleeve lengths, so any combination of those three fields will yield a valid product.

If I choose a size, then a color, and then a sleeve length, there are no issues. However, if I choose a color first, and then choose a size, it resets my color to the original, default color. The same thing happens if I choose a sleeve length first and then change one of the other options.

Is there any way to fix this behavior so that the customer doesn't lose their selections? I'm afraid that they might not realize that their previously-selected options have been reverted to the defaults and I might end up with orders for the wrong size, color, or sleeve length.

Thanks!


texts: How to print block generated by views in the tpl file?

texts:
I have a block with name: "Share Product"(block number 5) generated by my view with name: "main_product_deal". In this view i have 9 blocks.

Now in my .tpl file i need to print this block.

I have seen the function 'module_invoke' but not working.
My code is:

//On my tpl file
<?php
$block = module_invoke('views','block','view',"main_product_deal-block_5");
print $block['content'];
?>

I working in drupal 6.x. Is it correct my code? Or exist another solution?
Note: I can not set the block in the administration, because I'm programming certain things in the tpl

Thanks :D


texts:
I've made a content type User. Each user has a field email. I will not display the email but I would like a way for visitors to contact each user. So I am looking for a way to have a simple contact form inside a content type.

Any ideas?


texts:
When I edit my node I have this date

But when I save the system change the Time:

I really don't understand because my timezone on the server and drupal are the same.
And my field is well configured:

For your information

Thanks in advance


texts: What does INTERNAL form properties mean?

texts:
On the Drupal form-API page, there is this paragraph that reads:

  Note that internal properties are not included in the table below, but
  are included in the Properties list. These include: #built, #children,
   #error, #id, #input, #printed, #validation_arguments

What does "internal" mean, as compared to other form element property types?


texts: Pass data to hook_preprocess_html from custom module

texts:
I'm trying to create a custom Drupal 7 module where it renders a custom page template. I want the data on /animals and /animals/getanimal to be in a custom HTML template.

After much searching and few successes, I've found that hook_preprocess_html works and that I can stop Drupal from loading the default template, but I'm struggling to pass data to my templates from the menu hook.

Is there a way to pass data from the menu hook to hook_preprocess_html, or is there another way where I can load my own custom template from the URLs in my custom module?

/**
 * Implements hook_menu()
 * @return mixed
 */
function animal_farm_menu() {

  $items['animals'] = array(
    'title'           => 'Discover animals',
    'page callback'   => 'getDiscover',
    'page arguments'  => array(),
    'access callback' => TRUE,
    'type'            => MENU_NORMAL_ITEM,
    'menu_name'       => 'main-menu',
  );

  $items['animals/getanimal'] = array(
    'title'           => 'all animals',
    'page callback'   => 'getAnimal',
    'page arguments'  => array(),
    'access callback' => TRUE,
    'type'            => MENU_NORMAL_ITEM,
    'menu_name'       => 'main-menu',
  );

  return $items;
}

function getDiscover()
{
  $result = ['cat','dog','monkey','cow'];
  return $result;
}

function getAnimal()
{
  $result = ['cat','dog','monkey','cow'];
  return $result;
}

/**
 * Implements hook_preprocess_html().
 */
function animal_farm_preprocess_html(&$vars) {

  $node = menu_get_object();

  $path = current_path();

  // echo $path;

  // Add a new theme suggestion when viewing node's of mynodetype.
  if ($path == 'animals') {
    $vars['theme_hook_suggestions'][] = 'html__mynodetype';
    $vars['data'] = [1,2,4,'monkey'];
  }

  if ($path == 'animals/getanimal') {
    $vars['theme_hook_suggestions'][] = 'animal_farm_discover';
    $vars['data'] = [1,2,4,'monkey'];
  }

}

/**
 * Implements hook_theme().
 */
function animal_farm_theme($existing, $type, $theme, $path) {
  $theme = array();

  //Add our templates/html--mynodetype.tpl.php to the theme registry
  $theme['html__mynodetype'] = array(
    'template' => 'html--mynodetype',
    'path' => drupal_get_path('module', 'animal_farm') . '/templates',
  );
  return $theme;
}


texts: Is it possible to add a pagination to a pdf when using views pdf module in drupal 7. Or is there any custom module.


texts: Programmatically Render a Node Edit form with a custom Form Display Mode

texts:
I'm attempting to make a page for users to edit data for a specific content type, but I only want them to have access to some of the fields not all. To do so I created a custom form display mode for content. I have a custom controller that is meant to display this form with a custom display mode. Here is the code meant to render it.

    public function showCustomForm() {
        $node = \Drupal::entityTypeManager()->getStorage('node')->load('123');
        $edit_form = \Drupal::entityTypeManager()->getFormObject('node', 'my_custom_form_display_mode_id')->setEntity($node);
        return \Drupal::formBuilder()->getForm($edit_form);
    }

And I get the error

  Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException:
  The "node" entity type did not specify a
  "my_custom_form_display_mode_id" form class. in
  Drupal\Core\Entity\EntityTypeManager->getFormObject() (line 184 of
  /var/www/mydomain/http/web/core/lib/Drupal/Core/Entity/EntityTypeManager.php).

I was using this How do I load a form with a specific form display (form mode)? as an example. But still had no luck.

How would I programmatically load a node edit form with a custom form display mode?


texts: Drupal 8: Read field value from $variables in preprocess_html

texts:
I've been wrestling with Drupal 8 for some time now and have run into a little problem.

I want to get a field value from a content type that I can use in my html--front.html.twig.
I can create a new variable that I can use in the twig template i.e

$variables['custom_twig_variable'] = 'Some important value';

Then in my twig template I would simply call this like this

{{ custom_twig_variable }}

The thing here is that I don't now how to "reach" my field value in the array $variables that is passed into the preprocess_html function.

Array (
  [user] => Drupal\Core\Session\AccountProxy Object (
    [requestStack:protected] => Symfony\Component\HttpFoundation\RequestStack Object (
      [requests:Symfony\Component\HttpFoundation\RequestStack:private] => Array (
        [0] => Symfony\Component\HttpFoundation\Request Object (
          [attributes] => Symfony\Component\HttpFoundation\ParameterBag Object (
            [parameters:protected] => Array (
              [_system_path] => node/4
              [_controller] => \Drupal\node\Controller\NodeViewController::view
              [_title_callback] => \Drupal\node\Controller\NodeViewController::title
              [node] => Drupal\node\Entity\Node Object (
                [values:protected] => Array (
                  [vid] => Array (
                      [x-default] => 4
                  )
                  [field_background_color] => Array (
                    [x-default] => Array (
                      [0] => Array (
                        [value] => ff00ff
                      )
                    )
                  )
                )
              )
            )
          )
        )
      )
    )
  )
)

How do I read the value of field_background_color?


texts: How to show taxonomy terms' description field on a node/add form instead of term title only in drupal 7?

texts:
I find it a bit disturbing that you cannot set which fields of taxonomy terms are displayed when you add a new node and have the terms listed.

There will be a bunch of terms which the user has to select one from. However, sometimes only showing a terms title wont be enough, so I'd like to also show a terms description when adding a new node.

How can you do that?


texts: How to create programmatically multiple URL alias of same taxonomy term?

texts:
I have category cars and I want to create its URL alias according to the region like if the user location is Australia than URL will mysite/australia/cars similar if the user location is USA than URL will be mysite/usa/cars.

Can you please anyone tell how can I achieve this kind of functionality?

Thanks in Advance.


texts: Get all submissions from specific webform

texts:
I am trying to load webform submissions by a particular webform sign_up.

Using Query webform submissions, this does get me all the IDs associated and I can load the data using

$query = \Drupal::entityQuery('webform_submission')
  ->condition('webform_id', 'sign_up');
$result = $query->execute(); // Gives me IDs associated with the "sign_up" webform.

$storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$submissions = $storage->loadMultiple($result);
$submission_data = array();
foreach ($submissions as $submission) {
  $submission_data[] = $submission->getData();
}
// $submission_data now contains all the submissions from "sign_up" webform.

Is this the correct way of getting the submissions? I would think Webform comes with some sort of API to query the submission results.

I also tried: https://www.drupal.org/project/webform/issues/2902682 but ended up with an empty array.


texts: entityQuery condition for users without a role

texts:
In Drupal 8 - Is there a way to do a 'NOT IN' in a user based entityQuery?

$uids = \Drupal::entityQuery('user')
      ->condition('uid', 72)
      ->condition('status', 1)
      ->sort('created', 'ASC')
      ->execute();

This query ^ yeilds results

$uids = \Drupal::entityQuery('user')
  ->condition('uid', 72)
  ->condition('roles', ['testing_user'], 'NOT IN')
  ->condition('status', 1)
  ->sort('created', 'ASC')
  ->execute();

This query ^ does not. User 72 doesn't have the role 'testing_user'


texts: Aggregate & Compress CSS / JS Kills Metatag Fieldsets

texts:
I had to turn on aggregate and compress CSS and JS for my site as the performance was terrible and I was getting a lot of CSS errors (admin bar would disappear intermittently or not load correctly or other CSS errors)

Activating the aggregation improved page load times dramatically and solved all my other CSS issues, however, now I get an error with the metatag module in which the field sets for Open Graph, Facebook etc. won't load as hyperlinks which can be expanded, only plain text.

The issue seems limited to the blog content type.

Any ideas where I can look to solve the issue?


texts: Can I move the description of a form field between the label and the field?

texts:
I have a form with input fields such as this one:

'sex' => array(
    '#type' => 'radios',
    '#title' => t('Sex'),
    '#options' => array('m' => t('M'), 'f' => t('F')),
    '#description' => t("We use this to write Mr. or Mrs. in the letters we send you.")
)

By default, this prints the label first ('Sex'), then the radio buttons, and then the description. I would like to print out the label followed immediately by the description and have the radio buttons appear last. How can I achieve this? I know how to load a stylesheet, but in this case it would be nice for the html to appear in the correct order:
<input /> rather than <input />

Edit: The solution proposed by Anil Sagar works, but introduces a bug. Indeed, what I use his solution, it prevents me from giving a description to a checkbox field. In other words, if I write

$form['myCheckbox'] = array(
  '#type' => 'checkbox',
  '#title' => t('My checkbox'),
  '#description' => t("My description")
);

that description never makes it to the HTML. Does anyone know how to fix this?


texts:
I'm trying to create a custom field type which has several elements, one of which is an image. Is it possible to use an image field type within this form somehow? Most of the resources I find tell me to use a managed_file, but it seems I have to manage my own file in this case? As in move it from temp to public storage, create file_usage instances, and such? I don't really want to do that if I don't have to :)

As an example, I'd like to have something like the following in my hook_field_widget_form():

$element['iid'] = array(
    '#title' => 'Image',
    '#type'  => 'image',
);

I would also like to employ other features of the image field type, such as alt text and styles.

Edit: I should add that I've taken a look at the field_collection module, however the client I am working for has specified that modules without a solid version (those tagged as alpha, beta, or dev) are not to be used.

Edit 2: Looks like there's no way of using custom field types within your own custom field type. I ended up doing the file management myself by taking a peek at how the Image module does it's file management. Unfortunatey this means that I'm not taking advantage of image styles, although it looks like I could potentially do that by hand as well.


texts: how to create a page.tpl.php without $page['content']?

texts: The page.tpl.php of my website shouldn't contain <?php print render($page['content']); ?> because it is only set of blocks. The problem is I'm not able to insert comment form into node pages of a website which its page.tpl.php hasn't <?php print render($page['content']); ?> . what shall I do?


texts: Authenticated users missing from users_roles table

texts:
I have created several authenticated users in my site through the admin/people/create interface. However, these users are not showing up in the users_roles table. Is this a known issue or am I doing something wrong.

When creating these users I used fake emails, so authentication emails where not received. However, I've turned off the "require email authentication option." Also, when using dpm() on a variable the contains all the users created from a user_load_multiple I can see that they have a 2 in the user role. So why is it not in the database?


texts: How should I perform a redirect in hook_form_alter()?

texts:
When users log in, I want to redirect them to another page, when they have a certain role. In Drupal 7, I'd use drupal_goto() in hook_user_login() to do the redirect, and hook_module_implements_alter() to make sure that my module is last in the list, so that everything else gets a chance to run.

In Drupal 8, it seems that performing a redirect outside of a controller is not a supported use case.

On that page, gngn has the same problem, and manually generates a RedirectResponse and sends it.

The problem is that, as I see it, send() doesn't terminate the request and the page will have two HTML documents: a 'redirecting to...' page, followed by whatever page would have been there in the first place. Which could be a security issue.

johnvb notes this, and inserts a call to exit() after send().

Presumably something useful is being done in the $kernel->terminate() call in index.php, which is being bypassed by calling exit().

In Drupal 7, drupal_goto() called drupal_exit() to handle this problem.

drupal_goto() was removed says that modules needing to interrupt the request flow should throw an HTTP exception, but there are no 'redirect' exceptions.

As the user login also does a redirect, another approach would be to alter the redirection URL, as suggested on the drupal_goto() change record link above. However, that approach will result in my method being called on every single request, which for what I'm doing seems insanely wasteful.

So, how should I perform a redirect from hook_form_alter() in Drupal 8?


texts: How to override breadcrumbs defined by a module using a custom module?

texts:
Is it possible, using a module, to override a breadcrumd definition defined in another module's hook_node_view()?

Module property_bc sets a custom breadcrumb for nodes of type Property.
Module property_bc_plus wants to override that behaviour.

property_bc implementation of hook_node_view would be:

<?php
/**
 * Implementation of hook_node_view().
 */
function property_bc_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'property') {
    $breadcrumb = array();
    $breadcrumb[] = l(t('Home'), NULL);
    $breadcrumb[] = l(check_plain($node->name), "user/$node->uid");
    $breadcrumb[] = l(t('Properties'), "user/$node->uid/properties");
    drupal_set_breadcrumb($breadcrumb);
  }
}


texts: Created a module that has a form: How do I display on a page?

texts:
I just created a module called member_survey that just contains a simple information gathering form.

What I'd like to do is create a page with the url www.example.com/member-survey that contains the survey that i just created.

I can't for the life of me figure out how to do this. Can anyone point me in the right direction?


texts: Search autocomplete - what is the proper way to make it work for more that 13000 nodes?

texts: I use Search Autocomplete module, it works fine but only for small amount of nodes. I have more than 13000 nodes and this module just stacks. Is there a solution for this case?


texts: Import files into a file field in Drupal 7

texts:
I have a content type that accepts a PDF document as a file attachment.  I have a bunch of entries that currently have no attachment, but I have the files for each entry and need to associate the files with each of their respective entries.

Currently, all of those files are stored in public://publications, so they're already in the public file path where they should be, I just need to "hook them up".

Rather than hack this with Ruby which I would normally do, I'd like to kick the bad habit and use the Drupal API.  I've looked at the following articles:

Programmatically attaching files
http://drupal.org/node/330421

..but haven't been able to really wrap my head around it.

Curious if others have dealt with this situation and what they've done to address it.  Thanks.

UPDATE

I've got the files copying as they should be.  However, I'm not encountering an error, and the error happens during the node_save call.

Here is the error:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': INSERT INTO {file_managed} (filesize, status, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2); Array
(
    [:db_insert_placeholder_0] => 0
    [:db_insert_placeholder_1] => 1
    [:db_insert_placeholder_2] => 1330491978
)
 in drupal_write_record() (line 6975 of /var/www/website/drupal-7.4/includes/common.inc).

And here is the code.

$node = node_load($bib_value->nid);

$file = new stdClass();
$file->filename = basename($filepath);
$file->filepath = $filepath;
$file->filemime = file_get_mimetype($filepath);
$file->filesize = filesize($filepath);
$file->uid = 1;
$file->status = FILE_STATUS_PERMANENT;
$file->uri = $filepath;
$file = file_copy($file,'public://publications',FILE_EXISTS_REPLACE);

// THIS IS A PROBLEM LINE
$node->field_publication_attachment[LANGUAGE_NONE] = $file;

node_save($node);

If I comment out the line labeled THIS IS A PROBLEM LINE then no error occurs, but that obviously isn't desirable because that means it's completing but without attaching my file to the node!  Help!

SOLUTION

$node = node_load($bib_value->nid);

$file = new stdClass();
$file->filename = basename($filepath);
$file->filepath = $filepath;
$file->filemime = file_get_mimetype($filepath);
$file->filesize = filesize($filepath);
$file->uid = 1;
$file->status = FILE_STATUS_PERMANENT;
$file->uri = $filepath;
$file->display = 1;
$file->description = '';
$file = file_copy($file,'public://publications',FILE_EXISTS_REPLACE);

$node->field_publication_attachment[LANGUAGE_NONE][] = (array)$file;

node_save($node);

Needed to set display and description on $file as well as cast $file as an array when adding it to the attachment field.  All worked smoothly after that.


texts: Download count module does not work for me

texts:
I installed the Download Count module for Drupal 6. The automatic views were normally generated by the module. One of these views is file_download with a page format. The view should generate statistics, but I find no statistics generated by the view. I opened the view and I found everything is normal, unless there is something I am not aware of.

Did I miss anything?


texts: Is it possible to implement an express checkout with Drupal commerce?

texts:
I'd like to setup a product, where it's just a one page form customers fill out, and a button labelled 'Pay now'.

I don't want a list of products or add to cart functionality or anything like that. Just a simple form and a button. A confirmation page and email is fine.

Is it possible to do this with Drupal Commerce?


texts: Attaching assets if the page contains a table

texts:
I want to attach a CSS file to a page only if it contains a table. I tried

function my_assets_element_info_alter(array &$types) {
  if (isset($types['table'])) {
    $types['table']['#attached']['library'][] = 'my_assets/fancy';
  }
}

from the guide "Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module" but it does not work. The hook itself and the condition works. The question is where I have to save the #attached array in the $types variable?

I appreciate your help and feedback.

PS: The following hook attaches the CSS as expected:

function my_assets_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'my_assets/fancy';
}

Edit: While using the site I noticed that my CSS loads on sites like "/admin/structure/types". The Twig Debug hint says "THEME HOOK: 'table'". I guess this is important because it does not say this on the other tables I was waiting for to load the CSS.


texts: I need to set an auto response message on a Webform 7.x-3.19. I understand that I need to add a script which is going to do the job. My question is which php file should I edit to do so?


texts:
I have a content type with +3000 nodes, and it has a field set as Term Reference for countries. I would like to have a map that count all these nodes (maybe with Views), but all solutions I have found was to set a geofield using Gmap module, and in my case it will be hard to go through the +3000 nodes to give each node its location.

So is there is any module that can count nodes of each term, showing it on its country? Also if I would like to show only five countries instead of whole world map, is that a map library or map modules can do that?


texts: How to create a layout with different size grid theming with Views?

texts:
I recently saw this Wordpress website.

I am curious on how to create such a layout with different columns for each row in views.

Can someone help me out with this what to do?


texts: drupal single page Error 324 (net::ERR_EMPTY_RESPONSE)

texts:
I am having a problem I really can't figure out. I am running a drupal mobile website using mobile tools and I have also boost installed on drupal.
Now the mobile website works fine on m.domain.fr BUT ONE page doesn't work. It returns a Error 324 (net::ERR_EMPTY_RESPONSE) but all other pages ar ok.
This page is a view and I can access it just as expected in Views Editor, I have normal preview, but i can't access this page from web.

Any help would be welcomed.

Thanks


texts: Ability for user to flag or select multiple nodes from view listing

texts:
I am creating a page where I have a view listing about 100 nodes of a specific content type and then underneath that I have a contact form. When visitors (logged out users) come to my site I would like them to be able to select some nodes from this view that they like. Either with a checkbox next to each one of them or by some other flagging system. When they then complete my form the specific nodes they have chosen will be sent with the form submission.

Possible Solutions:

Create a template file for the view and add in a checkbox in front of each node.
Use the flags module and pass the selected nodes when submitting.

I've never done something like this before so any help would be appreciated!


texts: How can I submit a form into a node and save it in the database?

texts:
I installed drupal 8 in local and i have created a content type named 'Formulaire' and also i've created a FormulaireForm and i want to submit this form into that node .how can i do this ?
and i also want to storage this values into the database.


texts: Send email to specific users using webforms

texts:
In a view, everytime a user clicks on a link "click to connect" field, an email has to be sent to the specific username based on its id. I am using webform to send the mail. But, it restricts me to send all mails to the same email address.
In order to hide the email to which mail has to be sent, I am fetching the id of the user(to whom mail has to be sent) in a hidden field in webform. But, i cant figure out a way to get the destination email dynamically.


texts:
In drupal 8, I have added couple of facets at this page /admin/config/search/facets

According to the documentation I should now have some blocks to put on the search page.  But I do not see any blocks that represent those facets on the Admin block page(admin/structure/block)

the block for the faceted search does not show up when I look for it in place block modal dialog.

What step am I missing?


texts: Send email to users, except author comments

texts:
Hello!

I have node with field [field_users] (entity reference)

I create rule [after saving new comment]
Actions:
Loop for field: [comment:node:field-users]
inside loop i create var [users:mail]
And add action for sending emails...

But problem is:

if comment-author in list of field_users, emails sent also to author comment

Q:
How to remove comment author from loop?

Thanks for any help!


texts: drupal commerce ajax refresh cart summary upon select payment method

texts:
I have implemented a fee option in rules so that when people select a particular payment method, the current fees will apply, but I am now having problem, I tested deactivating all payment except for particular payment "a" and the fees are loaded as I understand it already refresh the cart with the "default selected payment and trigger the rule to insert the fees" but when I activate more then one payment and the default of payment is not payment "a", when I click on the payment method "a", its not reflecting the changes to the summary cart as I know the fees are inserted after that but in the sense of the UI its not acceptable.

is there any hook that we can use to refresh the cart summary everytime a payment method is selected?

help appreciated

thank you!


texts:
I want to show image in my solr search result page.
For that, I have created one field in my content type called media.

In db, Images are saving in field_data_field_media table in the form of field_media_value

Any help very much appreciated.

Best,
Latika


texts:
I'm trying to render both start and end date on a node template in Drupal 8 from the Date range field from the content type. I've tried multiple ways to no avail.

-- Only shows start date --

{{ kint(node.field_date_range.value ) }}

{% if node.field_date_range %}
{{ node.field_date_range.value|date(format='l M j') }}
{% endif %}


texts: How to get HTTPS url to work with Drupal Iframe Module?

texts:
I want to get HTTPS urls working as iframes. Now only http URL's work.

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

Is there a way to do that?


texts: User related content - field collection / views

texts:
I got a tricky situation. I'm working on Drupal 7.19 with Views 3.

I want to make a view in user profile page, that will show the user related content. Its sounds easy, but not exactly. The content is a photos, that are made as a field collection (one fields includes the image upload form, and couple text input fields). To get the latest fields from field collection data, I need to choose it as a view, and then pick all the fields I want to show.

My view with field collection fields need to be inserted as another field in parent view (its because the standard view doesn't allow you to choose the fields from field collection).

Well, at this point I managed to show the photos, but only all of them (not created by the  viewed user).

Can anybody tell me whats the solution, or just give some ideas?
In attachment you will find the screen:

The parent view:

The field collection view:


texts: How to stop spam user registration with Honeypot module?

texts: I'm using the Honeypot module in order to stop spam but still I'm getting the spam with same first name and last name. How to stop these spam user registration?


texts: Adwords conversion tracking on Ubercart store with payment gateway?

texts:
is it possible to implement Adwords conversion tracking so that it takes into account conversion that come through payment portal (Customer leaves site for a moment and returns after payment, usually conversion is not tracked due leaving site for a moment)?

I have injected adwords tracking code to order completion page but it tracks only orders that come with billing option (customer does not leave the site).

If this is not possible, is it possible to inject code to order review page, if so how? (This is bad as some customers wont complete order so leads to false conversions. Also we are planning skipping order review page for billing)


texts: Commerce - Product Type Best Practices, Blank Fields

texts:
Is there a best practice for when you should create new product types versus adding more fields to existing product types? Lets say you sell a bunch of different types of clothing, one of them being shirts. Say some shirts have specific fields like arm length, collar type, etc. and others just have generic fields like Size, Color, etc. Would it be best to have a generic product type called shirts and have EVERY possible shirt field on it, then just leave fields blank that dont apply when adding shirt products? Or, would it be best to have specific product types with ONLY the fields you would fill out for that specific product (which would mean the site could have a ton of different product types...long t-shirts, short t-shirts, collar shirts, long pants, short pants, etc).

I am having a hard time figuring out how to structure my products on the site im building (which involves many types of scientific instruments and industrial products). Some product types use the same fields but then have a few extra fields that not all products would use.

Is there a performance hit on having a generalized product type that has about 20 fields, or does it only really affect usability as far as how products are added to the site?


texts:
In my controller I want to return Drupal\Core\Render\HtmlResponse, and also I want to take HTML content from the template. The problem is that if I will try to render() a rendereable array before returning HtmlResponse - I'm getting "The website encountered an unexpected error. Please try again later." error. Array is being rendered correctly when I will just return it as it is, but with all Drupal HTML, which I don't want. What am I doing wrong?

Added #1: Discovery - all works well when I return Zend\Diactoros\Response\HtmlResponse . Now I'm even more confused. Why is that?

Added #2: When I use "renderPlain()" renderers method it also works, but I'm not sure of drawbacks yet.


texts: How to implement mobile website stored different url in cache database?

texts:
When a user visit our front page of website, we want to add argument behind the url, such as http://domainname.com?mobile=true.
Because we found that drupal cache system only stored same url one time in database, so if cache saved mobile site theme in database, a visitor may got wrong display of front page. So stored different url in cache database could solved this problem(Maybe).

We found that hook_boot() is called before cache working. So is there a method that add argument behind url?

This is what I implement store different cache in database.

  function newsyd_boot(){
    $current_url = $_SERVER['REQUEST_URI'];
    $is_mobile = newsyd_get_user_agent();

    $mobile_string = 'mobile=true';
    $is_contain = strpos($current_url,$mobile_string);
    if(!$is_contain && $is_mobile == 1){
        $http_pre = "http://";
        $destination_url = $http_pre.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        $destination_url .= "?";
        $destination_url .= $mobile_string;
        //echo "<!--";
        //echo $destination_url;
        //echo "-->";
        header('Location:'.$destination_url);
    }
}


texts: Change default Scald legend or caption output

texts:
I am sure the setting must be somewhere, but I only want to have the title as a default caption, the author field is irrelevant and the people updating content have to delete it each time.

Update:

I have found that going to Administration > Structure > Scald > Image (/admin/structure/scald/image/player/full/image_figure) I am able to alter the caption for that player, but not for the default player.

I have also found a hook in scald.api.php hook_scald_player(), but this is used like an info hook and using hook_scald_player_alter() does not alter the value:

function mymodule_scald_player_alter(&$players) { // tried referencing
  $players['default']['settings']['caption'] = '[atom:title]';
  return $players; // tried returning
}


texts: 'block/plugin' show a selected node. When editing the available nodes are filtered by type (or views)

texts:
There is a way to put a 'block/plugin' in a panel which, when edited by an admin, would have a list (using views if possible) of nodes to choose?

The idea is to place this 'block/plugin' in a pane of 'services', for example, and allow the admin to easily change the viewed 'node of type services' in a easy list. Something like node_pane, but not exactly the same.

With this I can say something like 'here will be a highlighted news, there will be 3 highlighted services' and so on.

Thanks in advance =)


texts: What is the form id used in user profile edit form?

texts:
I'm trying to alter some fields in the user profile form but I'm not sure why the form_id user-form is not working.

What I'm trying to achieve is to bring back the REQUIRED status of the password field which I turned off in user register form.

//USER REGISTER FORM
function MYMODULE_form_user_register_form_alter(&$form, &$form_state,
$form_id) {
$userID = \Drupal::currentUser();
$userRole = $userID->getRoles();
if($userRole[1] == 'ROLETOCATCH'){
$form['account']['pass']['#required'] = FALSE;
$form['account']['mail']['#required'] = TRUE;
$form['account']['roles']['campaign_manager']['#default_value'] =  TRUE;
$form['account']['notify']['#default_value'] = TRUE;
}
}

//USER FORM UPDATE
function MYMODULE_form_user_form_form_alter(&$form, &$form_state,
$form_id) {
    kint('hello');
}


texts: Getting the actual on/off value from a radio button instead of 1/0

texts:
I'm trying to store some data from an EntityForm to a txt-file.
This can be easily done with an entity wrapper, but when I get the value of the radiobutton (boolean) they selected I always get 1 instead of the value attached to that button (male/female).

This is my code:

$wrapper=entity_metadata_wrapper('entityform', $submission);
$wrapper->field_sex->value();  //this gives 1 instead of male


texts:
I have 2 content type (article and Album).

In articles I choose one or more albums using node references (autocomplete) to display it with the article, but I need only albums that are not added before in any articles to be appear in autocomplete not all albums

I try to make a view but I can't find how to make a nested query to select all albums title where id not in filed_article_album

also If I want to change them using hook_form_alter how can I change the field option and I have add more button

do you have any suggestion
Thanks


texts: How is LanguageNegotiationUrlFallback used?

texts:
I've been trying to get language negotiation to work on my site, in particular to try to find a workaround for this bug, which basically means I must have LanguageNegotiationUrl enabled and above all other detection methods in order for content to be editable.

I discovered this class - LanguageNegotiationUrlFallback.

Why doesn't 'URL fallback' appear in the list of detection methods at /admin/config/regional/language/detection? Does anybody know what triggers it?


texts: How do you use BLOCK_VISIBILITY_PHP, in hook_block_info, to hide a block?

texts:
I am user #1; I do have the PHP filter module enabled, but still my block is displaying, when I'd like it to be hidden. Here's my implementation of hook_block_info:

/**
 * Implements hook_block_info().
 */
function alerts_block_info() {
    $blocks['get_e_mail_alerts'] = array(
        'info' => t('Get e-mail alerts'),
        'status' => TRUE,
        'region' => 'sidebar_first',
        'weight' => 0,
        'visibility' => BLOCK_VISIBILITY_PHP,
        'pages' => '<?php global $user; if ($user->uid == 1) { return FALSE; } else { return TRUE; } ?>',
    );
    return $blocks;
}

Thanks.


texts: I'm in the process of leaving my current job, and that requires that all of my accounts be disabled.  Well, some of those accounts are user 1 accounts in a few of our Drupal sites.  Is it possible to just "transfer" user 1 to another account?


texts: Rendering two custom entity forms on the same page

texts:
I have two custom entities, Foo and Bar. Bar has a has_one relationship with Foo through an entity_reference column.

I'd like an admin page that combines the forms of both entities. Ideally it would look something like:

Edit Foo

Name: ...
Description: ...

Bars

Name        Description        val1        val2
bar1        ...                ...         ...
bar2        ...                ...         ...
bar3        ...                ...         ...

[ add bar ]

[ save ]    [ delete ]

Ideally there would be inline Bar editing.

At the moment I have custom entities set up to use _entity_form and so they are edited on separate pages. This isn't ideal given their relationship. What's the best approach for combining forms in this way?

Many thanks.


texts: Making taxonomy dropdown on the basis of previously selected dropdown of two different taxonomies?

texts:
I have two different taxonomies
Taxonomy 1:

Category
-music
-football

Taxonomy 2:

Sub-category
-Jazz
-Rock
-Fifa
-Russian Open

I have linked Jazz, Rock to music and
Fifa, Russian Open to football by term-reference field.

I have content type event, having term-reference to both Category and Sub-category. I want drop-down for sub-category should be populated after selection of Category.
Eg. if we select music as category then in sub-category only jazz and rock should be shown.


texts: How to access the view display's field list in row plugin options

texts:
I am trying to create a row plugin that would be similar to the plugin in date_ical. The difference would be that it wouldnt use the entity display but the fields defined in the view, thus allowing for example to place information from related entities.
To do this I would need to setup options in the options_form where i would select form the defined fields whih is the title and so on. Somehow i cant access the information about the defined fields. I keep searching the $this->view object and around, but cant find it :(. I am sure it has to be there. Please help !


texts: Why does the Path Breadcrumb module change URLs?

texts: I have a multilanguage site. I had a link to node/drupal_get_path_alias('node/15') and works perfectly identifying the language of the site, so it gets the correct path ("products" for english, "productos" for spanish). I have installed Path Breadcrumb, tried to configure, and to my surprise, the link which previously worked is rewritten to the incorrect language, instead of "/productos" is "/products". The link is in the main HTML, in the preprocess_page. Why does Path Breadcrumb rewrites a path instead of just creating the breadcrumb? I uninstall the module and all works as intended again.


texts: How do I delete an orphaned paragraph node?

texts:
I have a paragraph node which seems to have gone rogue, since it does exist (I found it doing a search using Search API), but it does not appear as content, so I cannot delete it from the user interface.

How can I properly remove it?


texts: How does resizing of images work with lighttpd?

texts:
I switched the Webserver from Apache to Lighttpd. Since then, resizing images according to the defined sytles (/admin/config/media/image-styles) does not work anymore.

Anybody knows what may be missing?

Edit: Added excerpt from phpinfo():

gd

GD Support: enabled
GD Version: 2.0
FreeType Support: enabled
FreeType Linkage: with freetype
FreeType Version: 2.4.8
T1Lib Support: enabled
GIF Read Support: enabled
GIF Create Support: enabled
JPEG Support: enabled
libJPEG Version: unknown
PNG Support:    enabled
libPNG Version: 1.2.46
WBMP Support: enabled

imagick

imagick module: enabled
imagick module version: 3.1.0RC1
imagick classes: Imagick, ImagickDraw, ImagickPixel, ImagickPixelIterator
ImageMagick version: ImageMagick 6.6.9-7 2012-08-17 Q16 http://www.imagemagick.org
ImageMagick copyright: Copyright (C) 1999-2011 ImageMagick Studio LLC
ImageMagick release date: 2012-08-17
ImageMagick number of supported formats: 206
ImageMagick supported formats: [.....Many!!]


texts: Show node's content moderation state in a view

texts: How can I display the current moderation state for the node in a view and filter on it?


texts: How to properly attach Google Maps Api to Drupal behaviors in Drupal 7?

texts:
So, I've posted on this elsewhere and I seem to either get half answers but they've gotten me closer to a solution but not over the finish line.

I'm trying to implement a custom Google Maps application that pulls data in from GeoJson views that I've made of an OpenLayers application that I've abandoned. The problem that I'm having is that if I follow the Drupal docs and wrap my code in a jQuery closure, then my Google Maps call back which is loaded in the global context is out of scope for the function.

I've written a simple module that loads a block of html with a map div, and then loads my google maps script externally in the footer. My map callback works when I load plain JS via my module, but not when wrapped in a closure and attached to a behavior. This poses two problems for me: 1) I can't use jQuery functions to get my data; 2) it's bad practice (as above). So, I guess my question comes down to how do I pull a callback on an externally loaded script into the scope of my Drupal behavior?

So loaded as plain JS this works:

 var map, alumLayer, chapterLayer, assocLayer, userLayer;
  function initMap() {
    map = new google.maps.Map(document.getElementById('json-map'), {
      zoom: 4,
      center: {lat: 38.43, lng: -90}
    });
 //ajax code to get map data here
}

But this closure attempt doesn't:

    (function ($) {
Drupal.behaviors.gmap_json = {
attach : function (context, settings){
  var map, alumLayer, chapterLayer, assocLayer, userLayer;
  function initMap() {
    map = new google.maps.Map(document.getElementById('json-map'), {
      zoom: 4,
      center: {lat: 38.43, lng: -90}
    });
}
}
};
  alert('it works');
}(jQuery));

So, I know that my problem here is scope, but I haven't yet found how to do this.Do I need to modify my callback trying to reference the behavior object somehow? Is there a way of mix and matching scoped jquery? Or best practices be damned, whatever gets it working?


texts:
I have core search in my site. When I search without entering any keyword there is following warning message fired;

  Please enter some keywords.

I just want to show all available results without firing any warning message.

Note: I don't want to use any extra module, or create a view with the Views module, for this tiny task. I just want to alter the existing site search.


texts:
I am trying to follow these tutorials (http://themery.com/dgd7/advanced-theming/forms/with-templates and https://www.drupal.org/node/1419390).

And I have created these files:

login_form.module

<?php

  function login_theme()
 {
    return array(
      'login_form' => array(
        'render element' => 'form',
        'path' => drupal_get_path('module', 'login'),
        'template' => 'login-form',
      )
    );
  }

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

    $items['cms/login'] = array(
      'title' => 'CMS Login',
      'description' => 'Interface untuk login CMS',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('login_form'),
      'access callback' => TRUE

      //'access arguments' => array('access content')
      //'type' => MENU_CALLBACK,
      //'access callback' => 'login_form_access'

    );

    return $items;
  }

  function login_help($path, $arg)
  {
    switch($path)
    {
      case "admin/help#login":
        return "Modul untuk menampilkan interface login CMS.";
        break;
    }
  }

  function login_form($form, &$form_state)
  {
    $form['username'] = array(
      '#type' => 'textfield',
      '#title' => 'Username',
      '#required' => TRUE
    );

    $form['password'] = array(
      '#type' => 'password',
      '#title' => 'Password',
      '#required' => TRUE
    );

    $form['submit_button'] = array(
      '#type' => 'submit',
      '#value' => 'Login'
    );

    return $form;
  }

  function login_form_validate($form, &$form_state)
  {
  }

  function login_form_submit($form, &$form_state)
  {
    $pesan = '';

    try
    {

      $hasil = db_query(
        "select * from sys_userlis
        where
        username = :username AND
        password = :password
        ",
        array(
          ':username' => $form_state['values']['username'],
          ':password' => sha1($form_state['values']['password'])
        )
      );

      if($hasil->rowCount() > 0)
      {

        while($baris = $hasil->fetchAssoc())
        {

          $pesan = 'Berhasil login';
        }
      }
      else
      {
        $pesan = "Hasil query kosong";
      }

    }
    catch(Exception $e)
    {
      $pesan = "Exception $e";
    }

    drupal_set_message($pesan);
  }

and an empty template file: login-form.tpl.php

Both files are in the same directory: /sites/all/modules/login

So my code is a combination of two tutorials.
I want to make a login form and theme it with a template file.

With this code I got a page with 2 entry fields (username and password) and a submit button. While in fact the template file is empty.

What am I missing here?

Thank you.


texts:
I am creating a field formatter - a Drupal 8 version of a D7 field formatter module I wrote. I'm having a hard time getting it to work properly - there are a couple of issues, and I need some assistance in figuring out why this does not work.

As you can see in the code below, I've tried a couple different things in the render array - only when I have very simple html, in a "#markup" item, does it display. When I try the  it displays nothing - the field is completely empty, both visually and in the rendered HTML. And when I instead specify a '#theme' element my hook_theme() never fires. Additionally, I find that the viewElements method is only being called once - I have to do a cache rebuild in order to get the method to run again.

My ultimate goal here is put the field formatting into a template and just pass variables into it via the theme hook.

Seems like there's more than one issue going on here but I'm not sure where one ends and another begins.

This is the heart of the field formatter, in GdocFieldFormatter.php

public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = array();

    foreach ($this->getEntitiesToView($items, $langcode) as $delta => $file) {
      $file_uri = $file->getFileUri();
      $filename = $file->getFileName();
      $uri_scheme = \Drupal::service("file_system")->uriScheme($file_uri);
      if ($uri_scheme == 'public') {
        $url = file_create_url($file->getFileUri());
        $elements[$delta] = array(
          '#markup' => 'https://docs.google.com/gview?embedded=true&url=' . $url . '',
//          '#markup' => '',
/*          '#theme' => 'gdoc_field',
          '#url' => file_create_url($file->getFileUri()),
          '#filename' => $filename,*/
        );

      }
      else {
        drupal_set_message(
          t('The file (%file) is not publicly accessible. It must be publicly available in order for the Google Docs viewer to be able to access it.',
          array('%file' => $filename)
          ),
          'error',
          FALSE
        );
      }
    }

    return $elements;
  }

Here's the theme hook I wrote - but it's not firing and I don't know why. Note it is in gdoc_field.module

function gdoc_field_theme($existing, $type, $theme, $path) {
  return array(
    'gdoc_field_formatter' => array(
      'variables' => array('url' => NULL, 'name' => NULL),
      'template' => 'gdoc-field',
    ),
  );
}

So - several questions:

Why is the theme hook not being called?
Why is the  being stripped?
Why is the field formatter method viewElements only being called
once, after a cache rebuild, instead of on every page view (even with
caching turned off)?


texts: Node Access Product Module (nap) - Really embarrassing error message

texts:
I have built an Ubercart site, using the Node Access Product module, that sells only two products, one of which is access to a single node. Everything works correctly, but after the customer makes a successful purchase the following errors are repeated all the down the completed order page:

"Notice: Trying to get property of non-object in nap_save_purchase() (line 1508 of /home/mysite/public_html/sites/all/modules/nap/nap.module)"

and

"Notice: Undefined index: type in drupal_write_record() (line 7025 of /home/mysite/public_html/includes/common.inc)"

I have been everywhere looking for an answer. Can anyone help?


texts: I'm sure this is a very simple fix, but I'm new to Drupal and would be very appreciative if someone could help. I have a theme that I am using on a Drupal site. I make some changes to the underlying text in the themes PhP files (e.g. "Page not found" -> "Page is not found!"). I then reload the page and I do not see the changes on the site. I have tried clearing Drupal's cache and then reloading, but this also doesn't seem to help. After I make changes to a theme, how do I get them to show up on the site?


texts:
When the user is fill out my webform they are going be asked "who refer you to this page." The user would pick a user. I want to be able to send the results e-mail to that person programatically once they have submitted their question.

So I'm looking for a module allow me to e-mail the webform results base on  "who refer you to this page."?