How to change a custom field on form save In the node type page I've added one Integer field "field_article_rejected".
When in rejected stated it contains 1.

But when a registered user changes and "Saves" it I want to set the value of it to 0.

Also the registered user does not have read/write permission on this field. But if needed I can give the user permission for this field but I'll hide it in "Display fields"

How to do it?

I'm working on Drupal-6.

To explain what I'm doing: I've created an article directory. So an user will log-in and create an article type of page. So now this page will be shown as "Submitted articles" block using views.

But as an admin when I reject it then I want this article to be shown under "Rejected Articles" block to the user. So I want to use field "field_article_rejected". When 0 it means user has sumbitted and when 1 then it means rejected by admin.

You create a custom module that will include hook_form_alter().   Something like this:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    global $user;

    if (in_array('admin', array_values($user->roles))) {
      //admin role is not a default role
      //do nothing
    }
    elseif (in_array('authenticated user', array(values($user->roles))) {
      //remove editable field and replace it with a label
      $form['article_field_rejected']['#access'] = FALSE;
      $form['article_field_rejected_label'] = array (
         '#type' => 'item',
         '#default_vale' =>  isset($field['article_field_rejected']['#value']) ? $field['article_field_rejected']['#value'] : '0',
    }
    else {
     // For everyone else disable field and do not display it
     $form['article_field_rejected']['#access'] = FALSE;
    }
}

If you don't replace the field with a label, then the use can still alter the value by editing the browser.


Redirect user after one-time-login When users get an email with one time login link, they will arrive on a page to set their password (separated form via Password Separate Form)
But once they click submit, it doesn't redirect them to the normal view of the profile page.

How should I make the redirect?
I tried different Rules (Test 1, Test 2) and I even wrote to the module support of Password Separate Form, but nobody answer me and I need to fix the issue.

For people that want to have a separate form, here is my own solution:

I deinstalled Password Separate Form and, instead, installed Password Reset Landing Page (PRLP)
It does the redirect, the separate form and make sure people don't forget to actually set the new password.


How to access existing data in the row during Migrate? I'm using the Migrate module to import data but I want to compare existing data in my Drupal content for one specific field before I overwrite it during an update migration.

PrepareRow() doesn't seem to have access to the destination data.  I was hoping that Prepare() would as the inputs to prepare($entity, stdclass $row) suggest it has the entity in hand, however it appears that this entity is the fully constructed row it is about to import rather than the data from the destination object.

Is there any way I can get access to the unaltered destination row to do a comparison with my source row before the import happens?

Answer lies in PrepareRow() method you will implement... You always have access to source where reference to destination is given.. For example if you are importing a node you will have nodeid reference.. From node id you can get destination details using node_load api function..

Similarly for any other entity if you are updating you will have a reference in source using which you can load destination details...


How do I display labels in checkbox grid table? I managed to create table grid with checkboxes, however I can't get the label to display in first column. What am I missing, could you guys help ?

Thanks!

This is what I have in backend

Update:

Drupal issue: https://www.drupal.org/project/webform/issues/2951650

I was able to figure this out by creating a new custom element. My solution can be downloaded on my Github https://github.com/minnur/webform_checkboxes_table


Menu links at the corners of the screen Used omega theme and stumped at menu part.

Top right - Home
Top Left - Work
Bottom Left - Contact
Bottom Right - FAQ

Tried to set 2 menus: top and bottom in menu zone and then set id to each links so they can be positioned accordingly but it didn't work as expected. These menus sit next to the main menu in column 1, 3, 8

How do I put the menu links in menu block then set them at the corners of the screen?

For those that are not familiar with Omega theme, it will be hard to help you without more information like a link or your HTML and CSS code. However, you may look up the CSS float property to achieve what you want.


theme_table override not working I am trying to override / hook theme_table from theme.inc.
My theme name is stat.
I have added following function to my theme template.php.

function stat_table($variables) {
  //table logic here
  return $output;
}

I have dev env configured with xdebug and while function is 'loaded'/processed when displaying page with table, it is never called.
Original theme_table is called instead.
I already tried clearing cache via drupal_theme_rebuild();
Using Drupal 7.

Is there anything I am doing wrong?
How can I debug why is the function not called?

use hook_theme_registry_alter.

Example:

function MYMODULE_theme_registry_alter(&$theme_registry) {
  $theme_registry['table']['function'] = '_MYMODULE_my_table_theme';
}

function _MYMODULE_my_table_theme($variables) {
...
...
}


sites/drupal folder not pushed to git repository My .gitignore in the drupal root is as follows:

# Ignore configuration files that may contain sensitive information.
sites/*/*settings*.php

# Ignore paths that contain generated content.
files/
sites/*/files
sites/*/private

When I pushed it to a repository on github, the sites/default folder did not get pushed.

How to solve the issue?

I would add a README file under sites/default/files
then force the file to be added to the repository by executing git add -f sites/default/files/README and push your files.

The -f flag will allow the file to be added by overriding your .gitignore file.
The next time you clone the repository on a new location the folder sites/default and sites/default/files will be created by git.

When downloading Drupal the sites/default folder contains a file called default.settings.php. And one solution here would have been to add that file. But since your .gitignore excludes sites/*/settings.php default.settings.php file wont be added and Git will not add empty folders to the repository.


Create URL and redirect? function news_article_node_submit($node, $form, &$form_state)
{
// Make a URI link from title of pdf being uploaded
if (isset($form_state['values']['field_upload_import_pdf'])) {
    $file = file_load($node->field_upload_import_pdf['und'][0]['fid']);
    $filePath = file_create_url($file->uri);

    // Redirect to pdf
    isset($_GET['destination']);
    unset($_GET['destination']);
    if (isset($filePath)) {
        drupal_goto($filePath);

        // Return all field behaviors to redirect to default
    } else {
        $form_state['redirect'] = 'to page preview';
        drupal_redirect_form($form_state);
        }
    }
}

I was experimenting with drupal_goto() and $form_state['redirect'], but neither of them seems to work. Using drupal_goto() hijacks the whole module and the $form_state['redirect'] doesn't do anything. Also I am getting PHP errors when else function encounters the first two lines of code above:

  Notice: Undefined offset: 0 in news_article_node_submit()

  Notice: Trying to get property of non-object in news_article_node_submit()

Is there a way to create a URI from the filename, and redirect users to domainname://NAME_OF_FILE.pdf when choosing a conditional field while, at the same time, when users use any other conditional field, the behavior is the default Drupal one?

You can use the trick from the module File Force Download. You can check it in the their code repository https://cgit.drupalcode.org/file_force/tree/file_force.module?h=7.x-1.x


How can I debug adding libraries via hooks? I am trying to attach simple css via hooks in the themes and it does not work? The code looks correct to me. It doesn't attach. What am i doing wrong?

global-styling:
  version: 8.x
  header: true
  css:
    base:
      css/main.css:

  js:
    js/main.min.js: {}
    js/scrollreveal.js: {attributes: { defer: true} }
    src/js/vendor/picturefill/picturefill.min.js: {attributes: { defer: true} }
    js/custom.js: {attributes: { defer: true, async: true} }
    js/tp.widget.bootstrap.min.js: {attributes: { defer: true} }
    js/js.cookie.min.js: {attributes: { defer: true} }
    js/api.js: {attributes: { defer: true} }

  dependencies:
    - core/drupal
    - core/jquery

content-styling:
  css:
    base:
      css/content.css: {}

carousel-styling:
  css:
    base:
      css/carousel.css: {}

I am trying to attach css/content.css only when an entity reference to a paragraph is displayed.
I am trying to attach css/carousel.css only when an certain paragraph type (slider) is displayed

function porto_sub_preprocess_field(array &$variables, $hook) {

  if(  $variables['element']['#entity_type'] == 'paragraph' ) {
     \Drupal::logger('my_module')->notice('content should be');
        // tried both these on all
        $variables['element']['#attached']['library'][] = 'porto_sub/content-styling';
        $variables['#attached']['library'][] = 'porto_sub/content-styling';
  }
}

function porto_sub_preprocess_paragraph(&$variables) {
  $paragraph = $variables['paragraph'];
  if($paragraph->getParentEntity()->bundle()=='slider') {
    \Drupal::logger('my_module')->notice('carousel should be');
    $variables['element']['#attached']['library'][] = 'porto_sub/carousel-styling';

  }
}

Then i tried....still nothing

function porto_sub_page_attachments(array &$attachments) {
      $attachments['#attached']['library'][] = 'porto_sub/content-styling';
    $attachments['#attached']['library'][] = 'porto_sub/carousel-styling';

x    }

Is there some way i can debug? I get no information regarding what's wrong here.

To attach a library to a certain paragraph type you could use template_preprocess_paragraph__PARAGRAPH_TYPE() like following. Note how it's just added to the $variables array not the element.

function MYTHEME_preprocess_paragraph__slider(&$variables) {
  $variables['#attached']['library'][] = 'MYTHEME/carousel-styling';
}

Same with the field. Simply use template_preprocess_field__FIELD_NAME() and attach the library directly to the $variables array.

Your content-styling and carousel-styling libraries probably should look more like following. Note how it's added as theme category, not as base. See the docs on File Structure for some info about SMACSS.

content-styling:
  css:
    theme:
      css/content.css: {}

And finally: Flush cache, flush cache and flush the cache again!!!!!!!


Use CDN version of Video.js Until the Video JS Drupal project supports the CDN version, how can we go about overriding the default URL in a custom theme? It looks like there is a plan to include it in the future but not yet implemented.

You can use the following code in a module, or a theme.

function mymodule_js_alter(&$javascript) {
  if (isset($javascript[$path])) {
    $javascript[$path]['data'] = 'absolute URL to the file';
    $javascript[$path]['type'] = external;
  }
}

Replace $path with the correct value. Normally $path is build from the path where the module is installed with drupal_get_path('module, $module) . '/' $filename.


Find webform submission ID in a custom submission handler I have created a webform custom submission handler.

public function submitForm(array &$form, FormStateInterface $form_state,  WebformSubmissionInterface $webform_submission) {
  $webform_submission->getDate();
}

I am getting all the submitted values except the submission id. How do I get that value?

I have been able to get the submission ID in a custom submission handler using the following code.
$webform_submission->setSticky(!$webform_submission->isSticky())->save();
$sid = $webform_submission->id();


How to hide certain fields to a user if they aren't referenced in a field on the node? I have a content type which has a full content and teaser display. It has a number of fields, and one of the fields on it is an Entity Reference field which references users (called field_registered_users with unlimited values allowed).

If a user views the node and they aren't referenced within the field then I want to hide certain fields on the node.

How do I do this? Should I do it in the template file or through a custom module? I also want to display a block on the page instead of the fields if this is the case.

business logic never in tpl.

You could use hook_node_view($node, $view_mode, $langcode).

In my opinion the cleanest and the most drupal way would be to create a custom formatter (mymodule_field_formatter_info) in which you should pass
the returned value (1 or 0) of your business logic to the #access property of the field

Regards.


Ensure that all Cron jobs work correctly I have a Mobile APP with a Drupal 8 admin backend and I have almost 20 cron jobs running at least 15 times on the day. I'm using Ultimate Cron and Advanced queue modules for handling this. I know that to ensure that all crons running properly, the website should be opened at least once a day or make the crons on the server not on the Drupal site. But, my solution is to create one cron job on the
server hitting the website base url to just ensure that all crons will run. So, my question is, does this solution work?

Maybe.

Considering there are 20 cron jobs and they all run 15 times a day and you’re using advanced queue, I would make sure to test in your production environment timeouts and memory issues.

Personally I would use cron + drush making sure the php.ini for command line PHP has more than enough resources to accommodate whatever it is you’re doing.

drush cron-run

https://cgit.drupalcode.org/ultimate_cron/tree/ultimate_cron.drush.inc?h=8.x-2.x#n77


How to fix my Rule to notify authors of products by email at order completion? I'm trying to send email notifications to authors of each products (line-items) in the order at completion.

I have tried many things surrounding the rule below... that is now at a strange point in its life.

I can use the [commerce-order:commerce-line-items:0:commerce-product:creator:mail] trick, but that sends the mail only to the first product owner.

{ "rules_commerce_order_message_admin_order_notification" : {
    "LABEL" : "Commerce order message: admin order notification e-mail",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "3",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "message_notify", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "commerce_line_items" } },
      { "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "commerce_order_admin_order_confirmation",
            "param_user" : [ "commerce-order:owner" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:message-commerce-order" ],
          "value" : [ "commerce-order" ]
        }
      },
      { "entity_save" : { "data" : [ "entity-created" ], "immediate" : 1 } },
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "\u00c9l\u00e9ment de la liste courante" },
          "DO" : [
            { "entity_fetch" : {
                "USING" : { "type" : "commerce_product", "id" : [ "list-item:line-item-id" ] },
                "PROVIDE" : { "entity_fetched" : { "entity_product_fetched" : "Entit\u00e9 r\u00e9cup\u00e9r\u00e9e" } }
              }
            },
            { "variable_add" : {
                "USING" : { "type" : "user", "value" : [ "entity-product-fetched:creator" ] },
                "PROVIDE" : { "variable_added" : { "event_creator" : "Variable ajout\u00e9e" } }
              }
            },
            { "message_notify_process" : {
                "message" : [ "entity-created" ],
                "save_on_fail" : "0",
                "save_on_success" : "0",
                "mail" : [ "event-creator:mail" ]
              }
            }
          ]
        }
      }
    ]
  }
}

What's wrong with my rule?

Note:

I would prefer using the Rule, but out of desperation, I have also tried to give directly the email whit something like :

$order = commerce_order_load($order_id);
foreach ($order->commerce_line_items['und'] as $line) {
$line_item = commerce_line_item_load($line['line_item_id']);
$product_item = commerce_product_load($line_item->commerce_product['und'][0]['product_id']);
$product_author = user_load($product_item->uid);
$courriels = $courriels . '<' . $product_author->mail . '>,';
}
print substr($courriels, 0, strlen($courriels)-1);

Preface
I have the impression that there is indeed "something wrong" in your rule, but please allow me to start with some (constructive intended) critique about the rule you created ...
Your issue may be partially caused because of the naming conventions you used for the variables in your Rules Actions. Your rule processes thingies such as entity_created, list_item and entity_product_created, etc. And you didn't post many details about what this rule is supposed to actually do/achieve. So probably only somebody who knows how to "read" Rules in its export language, may possibly be able to understand your current rule.
Imagine how much easier it would be to READ your rule if you'd have used variables such as admin_order_confirmation_msg, line_item and ordered_product.
What your current rule seems to be doing
By using the kind of variable names I suggested, it seems to me that your last Rules Action is an attempt to send the entire content of the message that you created in your first Rules Action (to be delivered to commerce-order:owner as per that same 1st Rules Action). But in this last Rules Action you ask the Message Notify module to eMail that very same message to what appears to the eMail Id contained in a user object whereas that user object corresponds to the ordered_product in the line_item being processed.
To move on, let's assume you really want the entire order (of X line items) to be eMailed to each (cfr your Rules loop) user that matches a specific ordered_product in any line_item. If that assumption is wrong, then make sure to add another Rules Actionn to create another message (entity) specific to a single line item (which is what I'd do, so that these messages would only contain data about "a" line item, not all of them ...).
Maybe the message module is confused
I've never tried, in a rule, to send the same message "entity" via Message Notify module and also have that same entity delivered (saved) with the Message module. So could it be that you're just confusing the Message module?
And another cause of possible confusion is within the rules module, where sometimes it gets tricky to "save entities". So possibly adding an appropriate intermediat "save entity" action may also help (if nothing else helps).
Time for some basic Rules debugging
Just (temporary) add a Rules Action to "display a message" (located within group "System"). And show the actual value of your token event-creator:mail as part of that message (btw: this is a Drupal status message, not anything related to the message module).
Based on the actual eMail Ids that will be shown in those debugging messages, you'll know in which direction to move forward to fix your rule.
Maybe add 'Replacement tokens' to your Message entity
If anything above does not help to solve your issue, then it may well be that you can get it to work with the technique of Replacement tokens. For (way) more details on that, head over to the answer to What's the purpose of "Replacement tokens" of a Message type?. I'm pretty sure that using this technique you can create a perfect solution to your issue. If you have more questions about that, use this link.


how to use pdf reader module in drupal? im trying to make a simple pdf viewer or reader website running locally on my computer. Ive used the pdf reader, follow the instruction in README.TXT but still i can't use this. I can't seem to find the pdf reader. Any suggestion on how to achieve what i want?

You need to enable pdf module and create a file field in the content type where you want pdf to be visible and there are two option to display PDF file in the field display setting, select which ever you require. (You need to use the latest pdf.js to use first page display).

Note: you need to download pdf.js manually and add in project directory

Hope you are following this,
http://drupalcode.org/project/pdf.git/blob_plain/refs/heads/7.x-1.x:/README.txt


How to prevent certain bundled CKEditor plugins from loading There is hook_ckeditor_settings_alter() to change/alter CKEditor settings. But I can't find a way to prevent certain CKEditor plugins from loading.

I am trying to achieve similar behaviors as here: https://www.drupal.org/node/2546048#comment-10188390 but that is for wysiwyg module, we don't use wysiwyg module.

We can disable CKEditor plugins by following hook as show with the example for disabling image and image2 plugins:

/**
 * Implements hook_ckeditor_settings_alter()
 */
function MYMODULE_ckeditor_settings_alter(&$settings, $conf) {
  // Comma separate names of plugins to remove.
  $plugins_to_remove = 'image,image2';
  $settings['removePlugins'] = !empty($settings['removePlugins'])
    ? $settings['removePlugins'] . ',' . $plugins_to_remove
    : $plugins_to_remove;
}

(taken from my own article: http://kb.detlus.com/articles/drupal/drupal-7-disable-ckeditor-bundled-plugins/)


Limit the creation of tags I wish to create a taxonomy where the administrator users limit which terms can be tagged.

Suppose I have a vocabulary containing the following terms:

Football
Golf
Snooker

I want the tag autocomplete to show the tags that can be used. If I typed "Foo", the autocomplete should show "Football"; if I typed "Basketball," the autocomplete would not show anything, the node would submit, but no term is created.

Is this possible?

It looks like the Content Taxonomy modules provides the ability to do this.

Without this, you'd have to implement hook_nodeapi('presave') and remove terms that don't exist yet.

Not even Drupal 7 seems to allow this without a contrib module, even though it does have specific edit terms permission for each vocabulary. Strange.


How do I get a count of comments by querying the database table? I'm migrating my Drupal forum and trying to export MySQL base as CSV. Among other things, I need to get comment counts.

How can I achieve it?

To be clear, this is what I have up to now:

SELECT node.nid, forum.tid, node_revisions.uid, node_revisions.title, node_revisions.body
FROM node, forum, node_revisions
WHERE node.vid=node_revisions.vid AND node_revisions.vid=forum.vid AND type='forum'

And I also would like to get comment counts for every node.

To be even more clear, this is what I would like to get.

| nid  | taxonomy id | author   | title      |  body       |comments count|
|------|-------------|----------|------------|-------------|--------------|
| 3    | 2           | 1        | Topic 1    | Topic body..|(I need this!)|
| 7    | 3           | 3        | Topic 2    | Topic body..|(I need this!)|
| 2068 | 2           | 287      | Topic 3    | Topic body..|(I need this!)|
| 12738| 4           | 4        | Topic 4    | Topic body..|(I need this!)|

The last column is what I need to get.

I think you can do it using the following query:

SELECT count(comments.cid), node.nid
FROM node
INNER JOIN comments on node.nid = comments.nid
WHERE node.type='forum'
GROUP BY node.nid


How to use CURDATE() and INTERVAL in Drupal Database object syntax How to convert SQL query to Drupal Database object query. I have already tried many ways but I didn't get success.

# Get the records which are published in week
SELECT node.nid as nid
FROM node node
INNER JOIN field_date field_date ON node.nid = field_date.entity_id
WHERE from_unixtime(field_date.field_date_value) BETWEEN CURDATE() - INTERVAL 7 DAY AND CURDATE();

The above query is working fine in mysql.

Try db_query() function:
Solution -1

$query = 'SELECT node.nid as nid FROM node node INNER JOIN field_date field_date ON node.nid = field_date.entity_id WHERE from_unixtime(field_date.field_date_value) BETWEEN CURDATE() - INTERVAL 7 DAY AND CURDATE()';
$result = db_query($query)->fetchAll();

Solution-2

$query = db_select('node', 'n');
$query->fields('n', array());
$query->innerJoin('field_date', 'fd', 'n.nid = fd.entity_id');
$query->where('FROM_UNIXTIME(fd.field_date_value) BETWEEN CURDATE() - INTERVAL 7 DAY AND CURDATE()');
$result = $query->execute();


Drupal 7 and ajax issues I have been Googling and trying to find out why when I perform a ajax callback that the form's submit function is also called. I looked at the ajax documentation and see no mention of this behaviour. Is this suppose to happen and how do I stop it if need be?

Thanks.

The submit function is where you should be executing your code. If you are executing your code in the ajax callback, you are probably doing it wrong. The ajax callback should only return what is needed to be returned. You can use logic to check things in the form generation function (like checking variables to change parts of the form), but any logic needed to be run on form submit, should be done in the form submit function/s.

function myform_example_form($form, &$form_state) {
  $form = array();
  $form['submit'] = array(
    '#type' => 'submit',
    '#prefix' => '
',
    '#suffix' => '
',
    '#ajax' => array(
      'callback' => 'myform_example_ajax_callback',
      'wrapper' => '#myform',
    ),
    '#submit' => array(
      'myform_example_submit',
    ),
  );
}

function myform_example_submit($form, &$form_state) {
  // do stuff here.
}

function myform_example_ajax_callback($form, &$form_state) {
  return $form['submit'];
}

If you really need to stop the submit function on a submit button you can do it by setting #executes_submit_callback.

eg.

function myform_example_form($form, &$form_state) {
  $form = array();
  $form['submit'] = array(
    '#type' => 'submit',
    '#prefix' => '
',
    '#suffix' => '
',
    '#ajax' => array(
      'callback' => 'myform_example_ajax_callback',
      'wrapper' => '#myform',
    ),
    '#submit' => array(
      'myform_example_submit',
    ),
    '#executes_submit_callback' => FALSE,
  );
}


Drupal Field Hierarchy or Fields By Selection Is there any modules that support a hierarchy for fields?  Nodes and fieldable entities in drupal seem so monolithic.  For example customers could be categorized into three categories:

Customer A
Customer B
Customer C

When customer A is selected then I only want specific fields shown according to that selection, and would be different for B and C.

I know I can do this via a hook_form_alter using the ajax callback attribute but wasn't sure if there was something already created for this.  I seen the hierarchy module but seems to be specific towards taxonomy.

I think the Conditional Fields module could provide a solution for you.

  Define dependencies between fields based on their states and values.

  Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.


How to implement a searchable addresses database (for a form)? I'm not sure if I should ask this type of question in this site, but I already tried to ask in the Drupal forum here with no reply so far.

I'm trying to find out the best way to implement a solution in an existing Drupal 7 site that must meet the following requirements:

a option to import addresses to the database from a csv/xls file, with:

fields: id, city, locality, street, street-number, postal code
around 100000 records/addresses

a form that include a address section/field(s) with a search functionality to search the addresses

where the user would fill up some of the address fields (ex: city, street; or just street)

and it would show a list with the matched addresses
that would be sorted by relevance

for example: is more relevant if it's found in both "street" and "city" fields, than only in the "street" field
(ideally it would be nice to replicate the google maps search)

a option to export the submitted form values to a csv/xls
  (if this is too of topic, just ignore this step (3))
(The site is on a Drupal 7, with mysql 5.5, and php 5.5)

Previously the client had tried to implement the import requirement, but it was to slow (a few days just to load the csv file), using the feeds plugin and a taxonomy structure to save part of the address fields.

I'm relatively new to Drupal backend development, mostly frontend, theming (templates with html, js, css/sass, and just a bit of php) in Drupal and doing some simple forms in backend, but I have some MySQL and PHP background.

So I was thinking in building a module to:

create database tables of:

addresses (fields: id, city, locality, ...)
addresses_searchable, where it would have addresses strings fields, by converting the strings:

to lowercase
replacing non-latin text to US-ASCII (ex: "á", "à" to "a")
in order to help speeding up the search

when using "like" in Drupal database search api

form_submitions (fields: id (of the submitted form), name, ... (other form fields) , adress_id)

create a form
. using ajax to load the search addresses list by pressing a button
set up a backend page (using permissions) for the import and export pages

import:

include a button to load addresses file (csv/xls), and other to run latest loaded file, and show a progress bar, and a log with possible errors

export:

using a button to download all form submissions up to now, or up to / after a selected date

From what I researched so far:

for reading files:

xls: could use the Drupal module phpexcel
csv: by using PHP native functions

to search the addresses:

by checking the Drupal api,

(in https://www.drupal.org/docs/7/api/database-api/dynamic-queries/expressions)
it doesn't seem possible to do relevant searches, like using the MySQL Match function:

SELECT *, MATCH ('city','street',...) AGAINST (':adressInputText' IN NATURAL LANGUAGE MODE) as 'relevance' ...

there is a Search API module that maybe would be the way to go

I haven't used it before, but maybe it would work if i create a entity for the address with the matching fields. Would be faster that a dedicated table?
in case it's better this way maybe, i could still use the address table as a temporary table, just to speed up the importing of the csv/xls addresses file

I'm not sure if this is the best approach to the problem, and what are the best practices to implement this in Drupal 7.
Or even if it is something that should other solution/framework like for example:

use something like Laravel (v5.4) (which i also would have to learn), and load the forms in Drupal 7 through a iframe that would show the form from the other server and framework.

I've searched Google but I’m still a bit confused. Can someone point me in the right direction?

My first approach would be to build a basic importer using the BatchAPI and create a custom entity to hold the address data (NOT a content type), combined with Address Field for proper storage.

Then, I would use Search API and Search API Solr to index and store those entities, afterwhich you can build custom forms with Form API or use Views to expose and search the index - which will be much faster than Drupal db queries. Whenever possible, keep MySQL from doing work, as this is what will bog down your site.

This keeps things close to "Drupal native" while solving many of the performance issues you raised with Solr.

You can use Form API to build forms with #ajax callbacks to query and return data from Search API queries as well.

The import will never be lightning fast unless you're not using the Drupal API to store them as entities. When you don't store them as entities, you lose a lot of the flexibility of say, plugging into Views or Search API without a decent bit of work. You couldn't also add fields with field API, at that point it's just flat data, so say goodbye to easy addition of taxonomy fields or using Address Field.

With Solr constantly indexing new and updated entities, having the import be lightning fast isn't really a priority (IMO) as long as it is reasonable. If you have millions of addresses, Drupal will only be able to parse rows so fast, and a lot of this is due to the event system (save an entity, fields attach, hooks fire, alters fire, etc) on every call to entity_save. The price you pay in speed here is paid off later when you want to manipulate or integrate that data with the contrib space.

The gist I linked to was an experiment I was doing with the Data module and CSV files. This loads the entire CSV file and dumps its contents into MySQL using load infile. This will plant data into a database very quickly, but, as I said, you will have a lot more work trying to get Drupal to recognize, communicate with, and extend that data.

Another approach, totally non-Drupal, would be to import the data to a PostgreSQL (9.4+) database or a no-SQL equivalent, possibly even something like Firebase, and execute searches against that. Then again, this is almost the same as doing Search API + Search API Solr, except you'd have to build the wrappers to create and send queries to those servers. So, it is still valid to offload all of this work in a separate system just to crunch data. It really depends on how much programming you feel like doing.

Just to be clear, there are a handful of options here, it just depends on how much you can stomach if it doesn't use Drupal in some way. Personally, I would not want to give up the flexibility the Drupal API provides in terms of understanding your data model, and therefore, I would create a custom entity and start there. It will be slower, but in the end provide more points of integration for you in the module ecosystem.


file_unmanaged_copy - Any service alternatives? The functionality of the file_unmanaged_copy is exactly what I need. The only problem is: it's a global function which uses static service calls.
Since I need to unit test my class (and not to mention how I dislike hidden dependencies coming from global functions) I can't use it.

Am working with D8 since the very beginning, but am failed to find any OO alternatives. Has anyone faced the same situation? Any "Best-practises" or workarounds?

This changed in Drupal 8.7.0
See https://www.drupal.org/node/3006851
try {
  \Drupal::service('file_system')->copy($source, $destination, $replace);
}
catch (\Drupal\Core\File\Exception\FileException $e) {
    // Log or set message or doing something else.
}


Menu permission/visibility control I am in involved in developing a site builder using Drupal 7.  Since it is a site builder, I need a user to be able to create menu items based on their needs, and then edit those menu items - but not any other users.

Also, is it possible to create a sub-domain during sign-up (along the lines of Drupal Gardens)?

For the Drupal Garden's style setup, you should definitely look at Aegir.  It requires a bit of setting up, but there are loads of tutorials and screncasts - there are a couple of good ones here and here.

With regards to your menu question, that seems like a simple permissions question.  When you deploy your new sites, you'll obviously have to set up a user for the owner of said site.  If you ensure that user has a particular user role, you can set permissions at "/admin/people/permissions" for the core menu module.  Look under Menu around halfway down the page and check the box for Administer menus and menu items for your site owner's user role.


Entity form presents all taxonomy terms instead of vocabulary I create entity form and add entity reference taxonomy field, set it as select and specify options, but i get all terms instead of one vocabulary terms.

Any idea how to make it works?

here some code.

$taxonomyStorage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
$voc             = $taxonomyStorage->loadTree("my_vocabulary");

$array = [];

foreach ($terms as $term) {
    $array[] = [
        'tid' => $term->tid,
        'name' => $term->name
    ];
}

$fields['voc_type'] = BaseFieldDefinition::create('entity_reference')
        ->setLabel(t('Voc Type'))
        ->setDescription(t('Voc tag'))
        ->setSetting('target_type', 'taxonomy_term')
        ->setDisplayOptions('form', [
            'type'    => 'select',
            'options' => $array,
            'weight'  => -6,
        ])
        ->setDisplayConfigurable('form', true);

$fields['voc_type'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Voc Type'))
    ->setDescription(t('Voc tag'))
    ->setSetting('target_type', 'taxonomy_term')
    ->setDisplayOptions('form', [
        'type'    => 'select',
        'options' => $array,
        'weight'  => -6,
    ])
    ->setDisplayConfigurable('form', true)

    // I think you're missing this:
    ->setSetting('handler', 'default:taxonomy_term')
    ->setSetting('handler_settings', [
      'target_bundles' => [
        'my_vocabulary' => 'my_vocabulary'
      ]
    ]);

I don't think you need to manually gather the options and set them like that. The target_bundles setting should take care of that.


Test fails with custom configuration After creating a custom configuration for my module "module_name.settings.yml" simpletest fails with this message:

  InvalidArgumentException: Invalid database prefix: in Drupal\Core\Test\TestDatabase->__construct() (line 81 of /path/to/installation/core/lib/Drupal/Core/Test/TestDatabase.php)

I reinstalled my module and everything works. I load the configuration with the following code.

$config = \Drupal::config('module_name.settings');
$base = $config->get('module_name.variable');

Still, I can't run my tests. If I remove the content from my configuration, tests run again.
I'm using Drupal 8.3.4, Apache 2.4.18, PHP 7.0.8, and MariaDB 10.1.25.

Since your module provides a settings.yml file, it must also provide a mymodule.schema.yml file describing the config object that stores the settings.

The real error pertains to something along these lines, and not a database error:

The test did not complete due to a fatal error.
Exception Uncaught e ConfigSchemaCheck   86 Drupal\Core\Config\Testing\ConfigSc
    Drupal\Core\Config\Schema\SchemaIncompleteException: No schema for
    MODULENAME.settings in
    Drupal\Core\Config\Testing\ConfigSchemaChecker-&gt;onConfigSave() (line 86
    of
    /var/www/docroot/core/lib/Drupal/Core/Config/Testing/ConfigSchemaChecker.php).

By providing a schema.yml file, clearing cache and re-running the tests this should resolve itself.

Related:

https://www.drupal.org/node/2848879
Simpletest fails with "invalid database prefix" - no other information given

You have to be careful of this one, because any contrib module that provides a settings.yml without a matching schema will throw the same error. It is confusing because you can install the module in your main application, but when you install it with a test, it will error out.

It will be easy to narrow down which ones, because it will be one that is listed in your required modules var (protected static $modules = [...]) which is how I stumbled upon the Menu Breadcrumb issue I mentioned.


Using the youtube_uploader module, how do I upload the video as private, without hacking the module I have been able to achieve what I need by changing the module here:

function youtube_uploader_get_settings_form() {
  $ret['youtube_uploader_publishing_options'] = array(
    '#type' => 'radios',
    '#title' => t('Default privacy options'),
    '#description' => t('More info on !here', array('!here' => l(t('YouTube support page'), 'http://support.google.com/youtube/bin/answer.py?hl=en&answer=157177'))),
    '#options' => array('public' => t('Public'), 'unlisted' => t('Unlisted'), 'private' => t('Private')),
    '#default_value' => strtolower(variable_get('youtube_uploader_publishing_options', 'unlisted')),
  );
  //Added: 'private' => t('Private') - being the added code.
}

How do I achieve this without hacking the module?

hook_form_alter() is what you're looking for. This function, when invoked in any module, will let you modify any form array created/rendered by Drupal's form API. For example, in a module named mymodule you could add the following function in mymodule.module.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  //modify youtube_uploader_get_settings_form to add Private to #options array
  if($form_id == 'youtube_uploader_get_settings_form') {
    $form['youtube_uploader_publishing_options']['#options']['private'] = t('Private');
  }
}

function xxxx_custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'field_ui_field_edit_form' && isset($form['instance']['settings']['youtube_settings']['youtube_uploader_publishing_options'])) {
    $privateOptions = array('public' => t('Public'), 'unlisted' => t('Unlisted'), 'private' => t('Private'));
    $form['instance']['settings']['youtube_settings']['youtube_uploader_publishing_options']['#options'] = $privateOptions;
  }
}


How to require a user to be logged in to access files On my website I currently have a way for users to upload files.  It has been brought to my attention that these files are showing up in search engines.  I'm fairly new and this is not a desired effect.  As a way to fix this for now, is there a way I can restrict access to sites/default/filesto logged in users? Thanks!

You have to setup the private file system. You can do this on /admin/config/media/file-system.

Next you will have to alter your field to use the private file system instead of the public file system. If this field already has data, you can use https://www.drupal.org/project/filefield_paths to migrate the files from public to private


Inject a theme setting form into a block Is there a way to inject the theme settings form into a block so it could fix to the left-hand side of the page when admin logins?

The url that would be injected into the block would be

admin/appearance/settings/<theme_name>

You can create a custom block: https://www.drupal.org/docs/8/creating-custom-modules/creating-custom-blocks/create-a-custom-block

In the build() method, you can return the form:

public function build() {
  return \Drupal::formBuilder()->getForm('Drupal\system\Form\ThemeSettingsForm');
}


Pre-Built Theme, how to transfer header to blocks I am moving at a glacial pace at theming, even following guides, because I think I am having trouble understanding the relationship between all parts of drupal theming. If someone can help me with the following issue, it should make me better understand how I am to configure everything else

Basically, I want to know the ideal way to theme this header which is static html to transfer into a block or a region so that I can theme it. I initially just included it using php include statements, but realize this is not good practice in drupal, and am looking for  the proper way to do it.

             Login

                <form role="form">

Login Form

                            <input type="text" class="form-control" placeholder="Username">

                            <input type="password" class="form-control" placeholder="Password">

                                <input type="checkbox"> Remember me

                        <button type="submit" class="btn btn-ar btn-primary pull-right">Login</button>

                </form>

                <form role="form">

                        <input type="text" class="form-control" placeholder="Search...">

                            <button class="btn btn-ar btn-primary" type="button">Go!</button>

                </form>

Thanks for the help,

Matthew Beal

Essentially you have the User Login & Search Form blocks so you could add the following to your themes' .info file:

regions[login] = Login
regions[search] = Search

Clear the site cache and visit your Blocks page (admin/structure/block) and you should see 2 additional regions. Place the User Login block in the Login region and the Search Form block in the Search region.

In page.tpl.php in your theme, use the following code:

<?php if (!empty($page['login'])): ?>

   Login

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

<?php endif; ?>

<?php if (!empty($page['search'])): ?>

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

<?php endif; ?>

This will give you a starting point and you can start overriding output in your theme by using functions and templates. It should be possible to achieve almost the exact code you're looking for.

You're obviously using Bootstrap, have you tried using the Drupal Bootstrap theme as a starting point?


Add custom class to a particular menu I need to know how to add extra class to a perticular menu.For example i have custom menu "menu-header-let",This menu is rendering like below,

Help

Home

home2

Now i want add extra class to the ul like below

I used phptemplate_menu_tree(), but i need different class for each custom menu.If is override menu theme and adding same class for all custom menu.

I have no idea how to add different class when different custom menu renders in drupal.

please help me.

Well, the code in tutorial that beth mentioned has bugs and does not work. The best solution I've found up to now is this:

<?php
function YOUR_THEME_menu_tree($tree) {
  if (preg_match('/A unique string in your menu/', $tree)) {
      return '
' . $tree . '
';
  } else {
    return '
'. $tree .'
';
  }
}
?>

You can use any unique path or link title as string to identify the menu. This solution was inspired by a comment in the cited tutorial.


Add variations to coupons commerce module of drupal On my commerce site, I want to add a coupon which can be use for a particular brand or catagory (taxonomy : product attributes).I am using commerce module with drupal 7. Any one help me on rule making...

Sure, no problem. Just create a new rule that triggers on the event "Calculating the sell price of a product."

You want the condition: Entity has field, then choose the commerce_product. This is the product reference field that is inherent in line items.
Then, choose the condition: Entity has field again. Choose the brand entity reference field that you have built into your product type. Basically, you will be reaching through the line item, through the product the line item refers to, to hit the brand that product is tagged with.
Next, choose the condition: Data comparison. For Data to Compare, choose that brand reference field. For Data value, switch from data selection to direct input mode, then choose the brand you wish to target.

Finally, under actions, add one of the commerce line item actions based on the mathematical operation you wish to do with that brand price.

This should do it!


D7 serving node content to related subdomain I am using Drupal 7 with single installation. Requirement here is to serve node content which belongs to sub-domain

Example:

if user try abc.mysite.com then system will internally serve content from

mysite.com/node/abc but user will not see any change in URL

What i have tried so far but failed:

htaccess modification
Subdomain module
Drupal hook "hook_url_inbound_alter"

Here "abc" subdomain is dynamic as this is related to node content.

Please Help!!!

This should be pretty simple to do with some mod_rewrite rules.  Apache's mod_rewrite supports proxying requests.


how to pass the query parameters as default values in buildForm? public function buildForm(array $form, FormStateInterface $form_state) {
    // in D7 it was : $params = drupal_get_query_parameters();

$form['search_api_fulltext'] = array(
'#type' => 'textfield',
'#title' => $this->t('Faites une recherche'),
  // in D7 it was: '#default_value' => isset($params['search_api_fulltext'])?str_replace('+', ' ',$params['search_api_fulltext']):'',
);
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Recherche'),
'#button_type' => 'primary',
);
return $form;

}

there might be a better method as suggested in the comments.
I replaced

    $params = drupal_get_query_parameters();

by

    $params=\Drupal::request()->query->all();


How do I fetch the ID of the current entity? I am using an entityform as rendered entity reference field of an eck entity as 'landing page'

I need the form submission to include the title of the landing page.
My solution is to add an entityform field and make rules copy paste the landing page title into the field, when submitted.

The Rules trigger is 'After saving a new entityform submission'.

Now I need to somehow fetch the entity ID of the landing page, but how to get the ID from the current entity?

I tried to create a rules component that uses php to get the entity ID of the current entity (landing page) as follows:

{ "rules_get_node_from_current_path" : {
    "LABEL" : "Get landingpage from current path",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules" ],
    "USES VARIABLES" : { "current_landing_page" : {
        "label" : "Current landing page",
        "type" : "domain",
        "parameter" : false
      }
    },
    "DO" : [
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : {
              "select" : "site:current-page:path",
              "php" : { "code" : "list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);\r\nprint $id;" }
            }
          },
          "PROVIDE" : { "variable_added" : { "nid_txt" : "NID txt" } }
        }
      },
      { "data_convert" : {
          "USING" : { "type" : "integer", "value" : [ "nid-txt" ] },
          "PROVIDE" : { "conversion_result" : { "nid" : "NID" } }
        }
      },
      { "entity_fetch" : {
          "USING" : { "type" : "domain", "id" : [ "nid" ] },
          "PROVIDE" : { "entity_fetched" : { "landing_page" : "Landing page" } }
        }
      },
      { "drupal_message" : { "message" : "Current landing page title: [current-landing-page:title]" } }
    ],
    "PROVIDES VARIABLES" : [ "current_landing_page" ]
  }
}

..but that gives me the following errors:

  Notice: Undefined variable: entity in eval() (line 1 of
  /home/cdt/public_html/sites/all/modules/rules/modules/php.eval.inc(146)
  : eval()'d code).

  Notice: Undefined index: entity keys in entity_extract_ids() (line
  7874 of /home/cdt/public_html/includes/common.inc).

I ended up using panels and used %node:ID context token.


Callback function on block In order to create a search block with autocomplete, I'm trying to use a callback function.
But it doesn't work with my module.
This module is implemented on my homepage which is http://mywebsite.com/lastnews

Could you help me?

Here is my code :

//my module
function search_city_block_info() {
  $blocks['search_city'] = array(
    'info' => t('Search a city'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

//my block
function search_city_block_view($delta = ''){
    switch ($delta) {
        case 'search_city':
            $block['subject'] = t('Search a city');
            $block['content'] = drupal_get_form('search_city_form');
            break;
    }
    return $block;
}

//just for the callback for autocomplete
function search_city_menu() {
  $items['search_city_page_autocomplete'] = array(
    'page callback' => 'search_city_autocomplete',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

//the form with the search field
function search_city_form($form, &$form_state) {
  $form = array();
  $form['City'] = array(
    '#title' => t('City'),
    '#type' => 'textfield',
    '#maxlength' => 60,
    '#autocomplete_path' => 'search_city_page_autocomplete',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  return $form;
}

//the values for autcomplete
function search_city_autocomplete($text) {
  $results = array();
  $results['city1'] = 'thefirstcity';
  $results['city2'] = 'thesecondcity';
  drupal_json_output($results);
}

Try this
//the values for autcomplete

function search_city_autocomplete($text = NULL) {
$results = array();
  $results['city1'] = 'thefirstcity';
  $results['city2'] = 'thesecondcity';
  print drupal_json_encode($results);
exit();
}


How to add UNION with pagination in drupal 7 query? My query is like :

$query_club = db_select('club_members','cm');
$query_club->fields('cm',array('first_name','last_name'));
$query_club->group_by('cm.uid');

$query_network = db_select('network_members','nm');
$query_network->fields('nm',array('first_name','last_name'));
$query_network->group_by('nm.uid');

$query_club->union($query_network, 'UNION');
$result = $query_club->execute()->fetchAll();

And its giving me correct result.

I want to add here pagination,

$query_club = $query_club->extend('PagerDefault')->extend('TableSort');

But its not working. Can any one help me out

I got the solution. I added this whole query as in subquery like,

$query_club = db_select('club_members','cm');
$query_club->fields('cm',array('first_name','last_name'));
$query_club->group_by('cm.uid');

$query_network = db_select('network_members','nm');
$query_network->fields('nm',array('first_name','last_name'));
$query_network->group_by('nm.uid');

$query_club->union($query_network, 'UNION');

**$query_pagination = db_select($query_club,'club_network')->fields('club_network');
$query_pagination = $query_pagination->extend('PagerDefault')->extend('TableSort');
$query_pagination->limit(10)->orderByHeader($header);**

$result = $query_pagination->execute()->fetchAll();

And using custom form table $form['pager'] = array('#markup' => theme('pager'));
pagination working fine now


Add language filter at admin/structure/block/block-content I'd like to add a language selector in the form that filters.
I've added it though a hook form alter:

$form["#info"]["filter-language"] = [
  "operator" => "type_op",
  "value" => "language",
  "label" => "Block language",
  "description" => ""
];
$language_options = [];
foreach (\Drupal::languageManager()->getLanguages() as $lang_code => $language) {
  $language_options[$lang_code] = $language->getName();
}
$form['language'] = [
  '#type' => 'select',
  '#title' => t('Block language'),
  '#options' => $language_options,
];

That page is a view.

That means, you can simply edit the view and add fields, filters and so on in the UI. You can get there by finding the contextual links icon and clicking "edit view" or by going to "/admin/structure/views/view/block_content/edit/page_1".


views exposed filters capable for this? I try to create something like questionnaire using views exposed filters. I have a content type xxx with fields:

field_1 (with options a,b,c)
field_2 (with options a,b,c)
field_3 (with options a,b,c)

I have 9 nodes, each containing only one option (node_1 has only "a" option from field_1 selected, node_2 has only "b" option from field_1 selected etc... so together 9 nodes)

Task: User chooses from 3 dropdown lists. For example choices are (field_1 - a, field_2 - a, field_3 - c)

I need the result to contain :

node that has field_1 with option "a" checked
node that has field_2 with option "a" checked
node that has field_3 with option "c" checked

Is this possible to acheive using views filters or I need another solution? I would like to use any views solution  Thank you.

This seems to be a bug in the Views module. If you have an OR filter group, Views will incorrectly use INNER JOIN instead of LEFT JOIN in the query.

One solution is to patch Views - more info & patch: https://www.drupal.org/node/1766338

Another solution that is using hook_views_query_alter that changes the join type by modifying the query object: Changing an inner join to a left join in views 3.3?

A third solution (see comment below) is to check the "Reduce duplicates" checkbox for the filters in the OR group.


Views Slideshow: how to change items per slide based on screen resolution I have a Views Slideshow slider with 3 items per slide (see below).

I am looking for a way to make it change the items per slide number dynamically when the screen width hits a certain breakpoint -for example 2 items per slide on tablet screen and 1 item per slide on mobile screen.

Been trying for few days but without success.
I'm able to access the number of slides in the JSON
 var slideNumber = drupalSettings.viewsSlideshowCycle["#views_slideshow_cycle_main_publications_featured_slider-block_1"].items_per_slide;

Any ideas are welcome.

We use the Owl carousel for this.  It lets you specify four breakpoints and the number of slides to show.

There is a D8 recommendation for Flickity but it has some licensing restrictions.


Simple string replacement in views output? In Drupal 7, for a view where I wanted to replace every instance of 'am' with 'a.m.' (with a similar replacement for pm/p.m.) in the output, I did this:

function mymodule_views_post_render(&$view, &$output, &$cache) {
  if ($view->name == 'target_view') {
    $replace_pairs = array(
      ' am ' => ' a.m. ',
      ' pm ' => ' p.m. ',
    );
    $output = strtr($output, $replace_pairs);
  }
}

How do I achieve the same result in Drupal 8? The documentation for the D8 version of hook_views_post_render() is broken/incomplete, but it does mention strtr(), so I imagine something similar should work.

I've already figured out that my if statement will need to test against $view-storage->id() instead, and I've noticed that $output is an array (rather than a string) in D8, but I'm not seeing anything appropriate to target in that array. I am new to D8; can someone show me the way?

In your custom module, create module_name.views.inc file and add following code.

<?php
use \Drupal\views\ViewExecutable;
use \Drupal\views\Plugin\views\cache\CachePluginBase;

function custom_module_views_post_render(ViewExecutable $view, &$output, CachePluginBase $cache) {
  if ($view->id() == 'VIEW_NAME') {
    $html = \Drupal::service('renderer')->renderRoot($output['#rows']);
    $replace_pairs = array(
      ' am ' => ' a.m. ',
      ' pm ' => ' p.m. ',
    );
    $html =  strtr($html, $replace_pairs);

    $output['#rows'] = $html;
  }
}

Replace VIEW_NAME with your view name and clear drupal cache.


How can I play an already uploaded video inside an Amazon S3 bucket? And how can I use the String Authentication on it? I´m new with video module, and with Amazon S3.
I need a video (that I´ve already uploaded to an Amazon S3 bucket), to be able to be played inside my site. I don´t want to upload it again through Drupal.

This video needs to be private. I´ve read something about "S3 Query String Authentication" but didn´t get how to actually implement that in my site.

I´m not able to point to a video that´s already uploaded to a bucket. I can only upload through Drupal, or upload it to a folder inside my drupal installation. How can I just grab the video?

And Should I do that using string authentication? How can I avoid people that´s not logged in to see or link to the video? (I know that there´s no way to stop other people to copy your stuff, but I´ve read about hot links and would like to avoid that from happening if I can).

I need that video to be available for a long period of time for my users, I just don´t want them to post the link in other sites (and use my bandwith).

I´m pretty clueless. Please I would love some help if you can. Thanks!!!!
Rosamunda

I'm answering this, hoping I can help anyone else with the same problem.
If you're trying to play videos already uploaded to your S3 Amazon account, you won't find an appropriate Drupal Module to do so. (see this).
What I did is to get myself an Amazon Cloudfront account and protect the videos manually with an expiration date; then I pasted the video (using the player jwplayer), and I controlled the access to that node using any of the node access modules.


How do I set the exact post date timestamp as Views contextual filter? I need to display nodes that were created within a certain period of time.

Setting Date: Date (node) (content: post date) as contextual Views filter works super smooth. Now when I call archive/2014-04-01-10--2014-04-04-15 all nodes created between April 1st 10am and April 4th 3pm will be displayed.

But how can I set the granularity to also respect minutes (and seconds)? How to alter the date filter or how to write a custom timestamp contextual filter?

I think you only have to pass the hours and minutes in to your contextual filter.

I have a View with filtering between dates and the URL is like that:
http://mysite.com/myview?changed%5Bmin%5D=23-03-2013+12%3A24&changed%5Bmax%5D=23-03-2013+18%3A24

This is for the access data from 23-03-2013 12:24 to 23-03-2013 18:24.

Also, make sure you have enabled the Date submodule Date views as it provides some improvements using dates in Views.


The 'to' date field not updating Out of the box the date field can accept a 'from' and 'to' date parameters and the 'to' date field will auto update when the 'from' field changes. As work has progressed on my site the field no longer automatically updates. Any idea as to why this would happen?

I recreated the date field settings on a clean install of drupal. I installed/enabled views, ctools, and the date api. I enabled the date popup widget and created a dummy content type. The popup and textfield widgets for the date field do NOT auto update but the select list does. I guess this is how it is designed. Back to the drawing board on this one. the popup module could possibly be modified to allow auto updating.


How can I add a taxonomy terms as a CSS class to my views? I would like to add a taxonomy term as a CSS class to each view result. How can I do that?

You can add a field with the taxonomy term and then exclude it from the view.

Then add as many fields you wish to present, such as Title.

Finally, add a global: custom text, and specify for example:

[title]

Replace with your field names obviously. You can consult the "replacement patterns" that the Views module kindly provides.


Hide Year Attribute in Date Module I have created a date field that prints out the time for a list of courses offered at a local employment office. I have used a custom input format (h:i A) for the user to input their course start/end time. When the new course listing is created the date field displays 0000-4:30PM to 6:30PM. I assumed the 0000 is representing the year attribute which is selected by default and I am unaware how to change it’s default setting.

I have also included a screen captures below:

I’m still rather new to Drupal so I’m not sure what step I am missing.

System Information:

Drupal 7
Bartik 7.12

Intrigued by your question, I found the same issue with trying to use a date field to store a time as the date field stores a Unix Timestamp.

A Drupal 7 project called timefield allows you to store a time which has no relation to a date, even has duration, and display configuration. I have not used it in a live environment, but looks like a solution for you.


"Initial Menu Level" config in Block Layout not working Using Drupal 8...

Goal

There are 2 regions in the header. The top region holds the Level 1 menu links while the bottom region holds the Level 2 menu links (or child links of the top regions).

What I want is for the Who am I? and About to only show on the top region. That's easy, initial menu level is 1 and max num of menu levels to display is 1. That works great.

Problem

Problem comes along when I add the same menu to the bottom region and choose the following set up:

I thought that with these when a user clicks About on the top region, then the child links ("Just more links") of that menu link would be displayed on the bottom region. But nothing happens. It only works with the Who am I? link.

The only difference is that Who am I? points to /node/2 while About points to the homepage with an added ?parameter=value

Please check the following:

The link for the menu item should be <front>?parameter=value
The position and weight in the menu tree at admin/structure/menu/manage/MENU_NAME
This patch may be related


Cannot configure the Antispam module So I've installed a new Drupal 7 on my server, and installed the "AntiSpam" module with Drush. ([See Installing modules without FTP.)

I can't configure the module. When I open up the Configuration panel, I get an error message, saying:

  Akismet spam protection service requires a...

When I click on "Configure," I get dropped back to the Configure menu.

What did I miss? Drush didn't display any error message, and the module shows up in the modules page as enabled.

The module asks for an API key, as the description for the "Akismet API key" field on admin/config/antispam says:

  Please, enter here your Akismet API key. If you don't have one already, you can get it by simply signing up for a free account at Akismet.com. Note that this information is required in order to use the Akismet Service. Please, consult the Akismet FAQ for further information.

Drush doesn't report any error because there isn't any error to report. Only after you enable the module you can see its settings page, where you need to enter the API key. Even if you installed the module using the browser, you should not have seen any message about entering the API key.

If you cannot access the setting page to set the API key, you can:

Obtain the API key using the link I reported before
Use Drush to set the Drupal variable antispam_wpapikey

drush vset antispam_wpapikey $key

(Replace $key with the API key.)


How to theme each nodes in a taxonomy term page seperately in drupal 7 I know there are many similar questions but none of them gave me a correct solution for my particular requirement. In drupal 7 in taxonomy term page nodes are displayed as a row of nodes one below another. But I want the first node to be displayed with a bigger image in the first row and the rest of the nodes as two nodes per row. How can i do that programmatically.

this could be done with view.

Create a taxonomy view of the type page.
Set the path as taxonomy/term/% this will override the default taxonomy path and will show the views page instead.
Add the fields that needs to be shown in all the nodes accept the first one.
Add a contextual filter of taxonomy term id.
With in the pager settings give an offset 1 so that the first node is skipped.
Set the Format to grid and give number of columns as 2 so that it displays in two columns

The above steps will display all the nodes except the first one in two columns.

Next we need to create a block to display the first node.

With in the current view add a block.
Set the pager to display only one element without the pager being shown.
Add the required fields. (Image in the size you want etc.)
Add a contextual filter of taxonomy term id.
Now go back to the page view and add a header.
Select "Global:view Area"
Choose the block we created above form the drop down and tick "Inherit contextual filters."

Now your taxonomy page would display as you wanted.


How to set body field display programmatically on node type install? When hook_installing a new custom node type filled with custom fields I call field_create_instance($instance) where I also set the custom fields' display like so:

'display' => array(
  'default' => array( // view mode
    'label' => 'hidden',
    'type' => 'text_default'
  ),
  'teaser' => array( // view mode
    'label' => 'hidden',
    'type' => 'hidden'
  )
)

I also added a body field via node_add_body_field($type) but where can I set that body's display properties programmatically? Per default it's set to be displayed in the teaser view. I want to hide it.

You can access and alter the view mode configuration via field_bundle_settings(), (which is basically a shortcut to variable_get and variable_set):

$bundle = 'my_node_type';
$bundle_settings = field_bundle_settings('node', $bundle);
$bundle_settings['view_modes']['teaser']['custom_settings'] = true;
field_bundle_settings('node', $bundle, $bundle_settings);


How to use Webform's summed result in another node or block? First-timer here, a little background: I'm a pretty seasoned builder using tons of modules, but not a developer. Want to start diving into PHP-coding, just not that far yet. Please keep that in mind if you'd be so kind to answer... For now, there's something I want done.

I use the Webforms-module to gather registrations for an event. One of the fields on the form is numerical and holds the amount of persons registering. Works great. Webform gives me a nice analysis in which the submitted values for this field are summed, so I can easily see how many people to expect.

Now I want to use this summed value somewhere else as well. For instance on a page that is accessible by non-authenticated users (as opposed to the Webforms results view, that contains all the personal data I do not want to be public). So I need either some token that I can use elsewhere on the site, or another way of programmatically incorporating that value in a block or a node. Did my share of searching and found a lot, but nothing useful.

I just learned from Klaus Harris' blog how to write a very basic module that can show a page. But how do I get this piece of data where I want it? I took a peek in the webform.report.inc-file that's part of the module, but was rather intimidated by what I saw there...

Is there some way to do this that I can handle without first graduating as a Drupal developer? Or is this too big a jump?

It is kind of confusing to create Webform Views with aggregation at first, I'll try to give a detailed explanation.
First, you would create a View of "Webform Submissions" - use unformatted list of fields as format.

Remove all fields that are placed in your View by default.

Add relationship to "Webform Submissions: Data" as shown the screenshot below. Adding relationship to webform submission data is crucial for Summing up your field values, because the added relationship gives you an option to add raw value of your field to the View (otherwise SUM aggregation doesnt work - see here). So, you would select your Webform node by typing its ID or the Name of your form, then in "Component Data" drop-down you'll select the field which stores the number that you need to sum up.

Add the field to the View scope:
Select "Webform submission data: Numeric value(raw)", or " *: Value(raw)". They both will produce the result that you want.  Make sure you select the relationship that you added previously in the field relationship drop-down.

Enable Aggregation for your View and set Aggregation to "SUM" on the your numeric field. Watch your field result summed up.

See if this approach works for you.


Re-enable System theme file within a child theme I have the bootstrap theme installed.

I have a custom theme installed.

The bootstrap.info.yml file has the lines:

libraries-override:

# Remove individual stylesheets.
  system/base:
    css:
      component:
        css/components/ajax-progress.module.css: false
        css/components/autocomplete-loading.module.css: false
        css/components/tabledrag.module.css: false

In my custom_theme.info.yml file, how can I re-enable the ajax-progress.module.css file?

I've tried adding the following, thinking it would override it, but it doesn't seem to work.

libraries-override:

# Re-enable individual stylesheets.
  system/base:
    css:
      component:
        css/components/ajax-progress.module.css: true

One way of getting this to work is to add the CSS file as a part of your global-styling in custom_theme.libraries.yml

global-styling:
  css:
    theme:
      /core/modules/system/css/components/ajax-progress.module.css: {}

Hope this helps anyone who has come across this problem.


Form type markup states Is it possible to create a form element of type markup and add a state to it, to make it visible on a condition? I can't seem to make it work and get the error:
Warning: Undefined array key "#type" in Drupal\Core\Form\FormHelper::processStates() (line 211 of core/lib/Drupal/Core/Form/FormHelper.php)
I need to just add some text in the form and make it visible on a condition.
Any help would be appreciated, thanks!

Adding form type item did the trick:
$form['my_incomes'] = [
      '#type' => 'item',
      '#markup' => $this->t('My other incomes'),
      '#states' => [
        'visible' => [
          [':input[name="marital_status"]' => [['value' => 'single'],['value'=>'couple']]],
        ]
      ]
    ];


Views Contextual Filter by taxonomy in field collection I have a Drupal 7 project I'm working on that's got me stumped.
I'm building a site where the node (Decals) are applicable to models and years (This decal is correct for this model of this year).
Each product my be applicable multiple models and multiple years.

I created a content type that has a field collection of model and years that can have unlimited values. So far so good.

Where i'm stuck is i want to have a related decals block at the bottom, that would suggest additional decals based not the models and years that listed in the field collection.
I've creating a view of nodes that has a relationship to the field collection, but I can't figure out how to limit the results to only the models & years associated to the node.

Any suggestions would be greatly appreciated.

Once you have the Relationship to the Field collection, you can add all the other information you need (Relationships to Models and Years if necessary, you'll probably need them too).

Then if you go to add Contextual filters, you will see that Contextual filters for Models and Years fields have become available.

Configure each one to Provide default values from the node you're on (you choose that from the Drop-down under that option).

It's good to test Contextual filters one by one and make sure they work on their own before combining them.

Or in the Views Preview you can test by entering all/[year] to test the second one, or [model]/all to test the first one.

Then place the Block and test that they work in real environment, because Preview only tests the "from URL" part.


How to call a function in a form from another form? I have 2 forms: distribution_inscription_table_form and distribution_inscription_for_user_form in the same custom module (amap).

namespace Drupal\amap\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class DistributionInscriptionTableForm extends FormBase {
  public function getFormId() {
    return 'distribution_inscription_table_form';
  }
  public function buildForm(array $form, FormStateInterface $form_state) {
    some code...
    $rows = $this->_listEnrolments();
    some code...
    return $form;
  }
  public function _listEnrolments() {
    some code...
    return $rows;
  }
  public function validateForm(array &$form, FormStateInterface $form_state) {
    some code...
  }
  public function submitForm(array &$form, FormStateInterface $form_state) {
    some code...
  }
}

namespace Drupal\amap\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class DistributionInscriptionForUserForm extends FormBase {
  public function getFormId() {
    return 'distribution_inscription_for_user_form';
  }
  public function buildForm(array $form, FormStateInterface $form_state) {

    $rows = ????_listEnrolments(); <--------
    return $form;
  }
}

As they share a significant part of code; I put this code in a public function _listEnrolments located in the first form.
How can I call this function from the other form?

I created amap.services.yml

services:
  listenrolments:
    class: Drupal\amap\ListEnrolments
    arguments: []

and ListEnrolments.php

<?php
namespace Drupal\amap;
class ListEnrolments {
  public function __construct() {
  }
  public function list() {
    some code...
    return $rows;
    }
}

and in my two forms, inserted

$rows = \Drupal::service('listenrolments')->list();

at the right place.
And it works!


How to add a assign a value to File Field Desciption through tokens Have been struggling with this, I have a field collection that contains a selection list and will like to assign this value to a file field description in the same field collection, so the selected value becomes the file display name.

Many thanks, Peace!

You can use: $form['#attached']['js']  in your form preprocess to add some javascript that will set the field values.


Overriding a View table layout in module I'm trying to override a view table from within my module. I can't locate what the arguments are suppose to be and in what order (for my hook_theme func). I copied the theme file from views/themes and did no modifications. Does anyone know what is going wrong, and what should the arguments value be below?

My theme configuration is currently:

'views_view_table__opportunities_mentions' => array(
  'arguments' => array(
    'view' => NULL,
    'title' => NULL,
    'header' => NULL,
    'fields' => null,
    'class' => null,
    'row_classes' => null,
    'rows' => null
  ),
  'template' => 'views-view-table--opportunities-mentions',
  'original hook' => 'views_view_table',
  'path' => drupal_get_path('module', 'smd') . '/theme',
),

The easiest way to theme views is to edit the particular view in question and scroll down to find the link 'theme information'. This screen will tell you exactly what views theming templates that it is currently using and what templates you can make in your theme to override this output.

That essentially all views theming is - overriding the default markup with something to suit you designs.

@see http://www.group42.ca/theming_views_2_the_basics for an excellent tutorial on views theming

EDIT

If you want full control over the markup produced, and for this to be portable across themes, the only option you have is to create a custom module. This custom module could also have themeable components, and could even use a view to perform any heavy SQL (or you could just hand-write the SQL)

Take a look at a similiar module to get you started, and have a read through hook_theme


Pros and cons of exposed filters versus contextual filters I need to do some complicated filtering on my View and it seems that contextual filters lack the operators (e.g. between, greater than) available within the exposed filter configuration.  However, I don't want to user to be able to see or amend any filter widgets.

I can achieve this by setting the exposed filters to appear as a block and NOT assigning the block to the page.  I can then invoke the View by constructing a path with whatever querystring I wish and the filters are applied appropriately (e.g. www.mywebsite.com/myview?field_range=10&field_color=red).

Is there anything inherently wrong with this approach to using views, or any disadvantages?

Nothing wrong with your approach. i have used it myself a couple of times and seemed to have worked pretty well.

regarding the situation you faced, contextual filters are more sort of an argument rather than a filter so the miss the comparison operators.

The tool in view to use external input to filter is the exposed filter. that is what it is designed for and I think you can go ahead with this approach.


Composer update Drupal core, 8.5.1 to 8.5.2 Nothing to Install I am running Drupal 8.5.1, with php 7.2 and a new security update 8.5.2 was just released. Per the documentation, I should be able to update Drupal core with composer.

I ran the following command:

composer update drupal/core --with-dependencies

I keep getting :

  Nothing to install or update
  Generating autoload files
  Drupal\Core\Composer\Composer::preAutoloadDump
  Drupal\Core\Composer\Composer::ensureHtaccess

Has anyone have any luck updating a drupal site with composer? I usually update my Drupal sites manually but this is getting tiring. I do not trust drush for my updates.

You can try to delete the vendor directory and the composer.lock file, and then run the update again.

UPDATE:

You need to add the line "drupal/core": "~8.5.2" to the 'require' statement (or update it to whatever version you require).
Then remove the drupal/core line from the 'replace' statement.
Add the following line somewhere (at the end? I believe this should replace the existing repositories statement):

"repositories": {
  "drupal": {
    "type": "composer",
    "url": "https://packages.drupal.org/8"
  }
}

Then delete the vendor and composer.lock, and try again.

It should work.


Approach to removing extra space at beginning of RSS file? I ran the RSS xml file through W3C's RSS validator. The results say:

line 2, column 0: XML parsing error: <unknown>:2:0: XML or text declaration not at start of entity

I'm not sure how to approach this one. I searched on drupal.org and found these:

RSS Problem
XML Parsing Error: XML or text declaration not at the start of entity .... solution.

Based on the 2nd link, I tried placing an echo in the current template.php being used and the output appeared after the space right before the XML tag. That means the extra line in the RSS XML was placed there before the theming was invoked, right? Where should I look?

Someone left a space at the beginning of a module.

[space]<?php

You can either try to find that bit of code with some tool or command OR put this in includes/bootstrap.inc at line 1112:

echo $filename;

The line number could change subject to updates to Drupal 7 so make sure it is inside the drupal_load function:

if ($filename) {
    echo $filename;  //this is your included line
    include_once DRUPAL_ROOT . '/' . $filename;
    $files[$type][$name] = TRUE;

The result will be a long list of the modules being loaded in source code of the page.  The space will be right after the module with the problem.


How to render a field collection without default divs? I want to output a field collection using dl, dt and dd tags. The collection has two fields - field_heading and field_text. I want each field_heading to be a dt, each field_text to be a dd and to wrap the whole set in a dl.

I have achieved this by overriding field--my-collection--my-content-type.tpl.php and the field--my-field.tpl.php for the heading and text fields.

The problem is, a div is being generated on each item in the field collection (by the field collection module I believe). (div class="field-collection-view clearfix view-mode-full") This div wraps the heading and text elements together. The div is therefore inserted inside the dl but before the dt. This is a problem because the dt needs to be a direct child of the dl.

Is there a way to render the field collection without this div?

field--my-collection--my-content-type.tpl.php

<?php foreach ($items as $delta => $item){ ?>
    <?php print render($item); ?>
<?php } ?>

field--field-heading.tpl.php

<?php foreach ($items as $delta => $item){
    print render($item);
} ?>

field--field-text.tpl.php

<?php foreach ($items as $delta => $item){
    print render($item);
} ?>

You need to override theme_field_collection_view theme function in your template.php .


Post image with raw json? Using Content Type: application/json I tried like:

EDIT:

{
 "type": "article",
 "title": "Test article with image1",
 "body": {
 "und": [{
     "value": "test body!"
   }]
  },
 "field_image":{
 "und":[{
  "fid":{
  "filename": "bar.jpg",
  "target_uri": "sites/default/files/styles/large/public/field/image/bar.jpg",
  "filemime": "image/jpeg",
  "file":        "iVBORw0KGgoAAAANSUhEUgAAAKQAAAFzBAMAAABC179RAAAAD1BMVEUYooorZrPZwVO3Sd0M9BOSfwC2VwFIl7c9aAAAAABJRU5ErkJggg==",
   "filesize": "12345"
       }
     }]
    },

  "language": "und"
 }

Problem: Image is not created.

You need to use the file resource to upload the file first; that will provide you with a fid (file ID), which gets attached to the field on the node. The payload for that request might look something like:

{
    "filename": "foo.jpg",
    "target_uri": "bar/foo.jpg",
    "filemime": "image/jpeg",
    "file": "iVBORw0KGgoAAAANSUhEUgAAAKQAAAFzBAMAAABC179RAAAAD",
    "filesize": "12345"
}

And then to attach it the field your existing code will change to something like:

"field_image":{
  "und": [{
    "fid": [FILE ID RECEIVED FROM FILE SERVICE HERE]
   }],
}


Show a node (content) in a light box D7 I need to show a video in a light box on a site and am having difficulty. I thought I would create a normal page with the proper code but when I go to load the video the screen grays out then goes and loads the page but gets stuck as if it cannot do it. I also tried just creating an html file and loading it directly but it couldn't read it or failed or something. I am using fancy box and html 5 if that matters.
How would I do this? If you need more info please let me know
Thanks for any help guys

Edit:
I have tried the solution below which is what i need it just isn't quite working yet.
the url of the node is: http://fourcemag.com/homme/video and http://www.fourcemag.com/homme/video-0/video
so the last part of the url is video

This is the code:

function fource_preprocess_page(&$vars) {
  $path = $_GET['q'];
  $path = drupal_get_path_alias($path, $path_language = '');
  $patharray = explode('/', $path);

  if ($patharray[2] == 'video') {
    $vars['template_files'][] = 'page--video';
  }
}

This is the error:

page--video.tpl.php

not sure what is wrong here.
Please help
Same error as before

You will likely want to define a custom page.tpl.php for use in the lightbox so it doesnt conflict with your normal site pages where you would like sidebar content etc.

Think of having 2 differently themed versions of the same page, your traditional page and a cut down version which is only the node content area.

To do this, add a theme_preprocess_page() so it creates a unique url argument to trigger the content only display via its own tpl.php:

function YOURTHEME_preprocess_page(&$vars) {
  // Get the path (eg node/#) and split it into an array ([node][#][video])
  $path = $_GET['q'];
  $path = drupal_get_path_alias($path, $path_language = '');
  $patharray = explode('/', $path);

  // If the last part of the path is "frame" use the page-content.tpl.php
  if ($patharray[2] == 'video') {
    $vars['template_files'][] = 'page--video';
  }
}

Then copy your exiting page.tpl.php into a page--video.tpl.php and trim out all the content you dont wish to see in your lightbox.

EDIT: (include details on using the video only page) In your iframe load your node page with "video" appended to the drupal url. For example "node/135/video" so it using the page--video.tpl.php

I have been using this solution to embed content from our nodes into another application and it works well. :)


Displaying an image in a programmatically created block (Drupal 7) I have created a custom block module that will display the children of a taxonomy term and if a term has no children it will display the nodes of that taxonomy in a table.  The node type that they are showing were created using CCK and contain an image field and I would like to display the contents of the image field in this table.

So far I have only figured out how to be able to display the name of the node with a link and the time/date the node was last updated, but have not been able to figure out how an image might also be displayed.  Could anyone offer advice about how to do this or point me to some documentation on the topic?  Everything I found suggested that I should use CCK but for this particular problem I think I need to create my block programmatically.

EDIT:

function children_view_block_view($delta = '') {

  $block = array();
  switch ($delta) {
    case 'children':
      $path = explode('/', drupal_get_path_alias($_GET['q']));

      $tid = array_pop($path);

      $term = taxonomy_term_load($tid);

      // Set up the table rows and headers array
      $rows = array();

      $children = taxonomy_get_children($term->tid, $term->vid);

      $title = "Child Name";

      $header = array($title, 'Updated');
      // Add a new row for each child term
      foreach ($children as $child) {
        $rows[] = array(
          l($child->name, "taxonomy/term/$child->tid"),
          $child->vid
        );
      }

      // Set up the params for the theme_table call
      $table = array('rows' => $rows, 'header' => $header, 'empty' => 'No terms found');

      //$block['subject'] = t('');
      $block['content'] = theme('table', $table);

    break;
  }

  return $block;
}

Some code could help us help you. But as it is, why not creating the <img> tag yourself based on the file path found in the $nodevariable ?


How do I consume REST data with an external service? I want to integrate RESTful API with drupal 8.

What I want to achieve is my a project which is built in drupal 8 is the consumer and RESTful API is integrated into another website using CodeIgniter.

I want to create a page in drupal using routing and all data will be coming from another website.

Example:

http://mywebsite.com/products [drupal 8]
http://webservice.com/products/list.json [CI]

My website will consume web service of webservice.com and will display the products on my website.

What is the better way or structure to achieve it?

I actually have implemented a similar thing in my project.

I created a module structure like as follow.

 my_module [directory]
        products [directory]
          products.info.yml
          products.module
          products.routing.yml
          src[directory]
            Controller[directory]
              - ProductsController.php
          templates[directory]
              - products-list.html.twig
        my_module.info.yml
        my_module.module
        my_module.routing.yml

products.routing.yml

 products.list:
    path: '/products'
    defaults:
      _controller: '\Drupal\products\Controller\ProductsController::getList'
      _title: 'Get List'
    requirements:
      _permission: 'access content'

src/Controller/ProductsController.php

    /**
     * @file
     * Contains \Drupal\products\Controller\ProductsController.
     */
    namespace Drupal\products\Controller;

    use Drupal\Core\Controller\ControllerBase;

    /**
     * Controller routines for products routes.
     */
    class ProductsController extends ControllerBase {

      /**
       * Callback function to get the data from REST API
       */
      public function getList() {

        $data = array();
        $response = $data = $result = null;

        if (function_exists('my_module_reponse')) {
          $response = my_module_reponse('http://webservice.com/products/list', 'GET');
        }

        if ($response) {

          $result = json_decode($response);
          $data = array();

          // # add all the data in one multiple dim array
          $data['title'] = 'products to consume REST API';
          $data['users'] = $result;

          // display the content in the middle section of the page
          $build = array(
            '#theme' => 'products_list', // assign the theme [products-list.html.twig]
            '#title' => 'products to consume REST API', // assign the page title
            '#pagehtml' => 'data is coming from : products/list ', // assign the string message like this
            '#data' => $data
          ); // assign the array like this to access in twig file
        }
        return $build;
      }
    }

templates/products-list.html.twig

 {{ data.title }}

 {{ pagehtml }}

  {% for item in data.users %}

{{ item.yourproductnamekey}}

  {% endfor %}

my_module.module

      /**
       * @file
       * Test API module.
       */
      function my_module_reponse($url, $method = 'GET', $params = array()) {
        $methods = [
          'POST',
          'GET',
          'PUT',
          'DELETE'
        ];
        $result = array();

        try {
          if (empty($url)) {
            throw new Exception("Invalid url");
          }
          if (in_array(strtoupper($method), $methods) === FALSE) {
            throw new Exception("Invalid method");
          }
          else {
            // will need a request call for GET, POST, PUT
            switch (strtoupper($method)) {
              case 'GET':
              case 'POST':
              case 'PUT':
              case 'DELETE':
                if (function_exists('my_module_call_request')) {
                  $result = my_module_call_request($url, $method, $params);
                }
                break;
              default:
                throw new Exception("Invalid method");
                break;
            }
          }
        }
        catch (Exception $e) {
          echo $e->getMessage();
        }

        return $result;
      }

      function my_module_call_request($requesturl, $method, $params = array()) {

        // request url
        $url = $requesturl;

        try {

          // initialized curl
          $ch = curl_init();

          // set header for curl request
          $headers = array(
            "Cache-Control: no-cache",
            "Pragma: no-cache"
          );

          // set required setting with curl configuration
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
          curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
          curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);

          // pass the additional values
          curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));

          // close the curl connection
          $result = curl_exec($ch);
          curl_close($ch);

          return $result;
        }
        catch (Exception $e) {
          echo $e->getMessage();
        }
      }

products.module

    /**
     * implements hook_theme();
     * description: create the file as per below
     * eg : products-list.html.twig  for "products_list"
     */
    function example_theme($existing, $type, $theme, $path) {
      return array(
        'products_list' => array(
          'variables' => array(
            'pagehtml' => NULL,
            'data' => NULL
          )
        ),
      );
    }

Each submodule will contain the individual routing file and function related to each page. It will make easy for you to maintain the code as well.


How to add another condition to a specific active facet? I did try to add a condition using hook_views_pre_execute or hook_views_query_alter, but since Im usiong SearchAPI, theres is no point apparently in using these functions (no $query in views_query_alter, and no query too in views_pre_execute

Maybe using hook__search_api_query_alter could d othe trick but I dont know how to implement it.

My question is : How can I achieve this ?

Knowing that I need to add anoteh condition only when items of a specific facet are active (among a few other facets).

The solution is quite simple :

function mymodule_search_api_query_alter(SearchApiQueryInterface $query) {
    if(preg_match('/PRETTYPATHID/',url($_GET['q']))){
        $base_filter = $query->createFilter('AND');
        $base_filter->condition('MYFIELD', NULL, "<>");
        $query->filter($base_filter);
    }

}


How can I consistently see the "renderable" version of a views field? I created a custom views style plugin. I currently use:

$value = $view->field[$label_column]->getValue($row);

to get the value of the field. However, I was recently informed that this does not work for list fields(like 0=>'yes'=, 1=>'no'). This original line displays 0 and 1 instead of 'yes' and 'no'. This user suggested I use:

$items = $view->field[$label_column]->getItems($row);
$value = $view->field[$label_column]->render_item(1, $items[0]);

It seems like this solution does not work on standard fields. I also recently found that the original line does not respect field rewrites. Is there a universal way to see the field value after rewrites, while also respecting lists?

Use advancedRender(), this is a method in the base class of views fields, which renders an entity field respecting field rewrites and other settings:

$value = $field->advancedRender($row);


How can I remove zombie Panel menu item links caused by Features? I have a site that uses several panels, each of which has a menu link.  Recently I decided to remove the links on my local dev copy.  I updated my feature (which contains the panels) and then reverted on my host... But the links were still there.

Because the links are provided by Panels in code, they can't simply be deleted from the menu.  How can I delete these links?

To fix this, disable and then re-enable each Panel one-by-one on the production server.  Hope someone finds this useful!