How to change the output field date in a view? I want to alter a field 'Date' in the view to display only year using 'hook_views_query_alter', so that I can display only Year in the date field.
I'm trying below code, which is not working. Can anybody help me?
I'm not sure about assigning new value to the field in the code.
function alb_jobs_views_query_alter(&$view, &$query) {

  if ($view->name == 'test-archive') {
  $query->where[0]['conditions'][0] == array('field'=>"field_data_field_issuu_date.field_issuu_date_value","value"=>'%YEAR(STR_TO_DATE(field_data_field_issuu_date.field_issuu_date_value,"%Y"))%',"operator"=>"LIKE");

  }
}

Here is my date field screenprint:

If you are asking for the how to get year from date and use the year in view query alter then

You can use strtotime();

$year = date('Y', strtotime($field_data_field_issuu_date.field_issuu_date_value));

Another way in view you can use custom date format on display and show only year and use that value.(Depends on requirement)


How to redirect a user upon Login? This is the scenario if the user logs in from the home page <front> he should be redirected to dashboard. If he logs in from some other page he should be redirected to the same page. I think that Login Destination and Login Taboggon can do this, but I am not sure how to use them both.

By the way I am using D7.

You can also use the rules module. You can add a rule which does a redirection after successfull login.


Edit a node via code authentication I'm creating a website and I have to give the possibility for an anonymous user to update a node. The node is recognized through the use of a code, code that I am sending to the user when the node is saved for the first time. And when I save this node (for the first time), the node is modified to ensure that it is owned by user X and not by anonymous. Ok, is a little complicated, but these are the requests from my client.

So, I send to the user a mail with this line into: http://DOMINIO.EXT/node/123/edit/codeSHA1.

My problem is that Drupal obviously tells me that access is denied to perform the edit operation (node uid is X, but I'm uid 0) when I click onto that link (in my email client).

How can I resolve this "problem"? I don't want to install TAC or TACLITE, but I can write PHP code into one of my custom module.

Here is a solution using custom coding.

Store all hash codes that are the access code to the DB (I think you do this already), a word of caution do not do md5(node id) or sha1(node id) as anyone will be able to figure it out.
Enable anonymous users to edit the content type they are submitting where the code is needed to edit the node. I know what this mean, keep reading.
Create a custom module where you are going to use the NODE API to intercept the node edit step.

If Drupal 6:  http://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook_nodeapi/6

function YOUR-MODULE-NAME_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'prepare':

    // Add PHP Code here to validate the hash code
    // You can use an if/else condition to print an access denied message
    // if the code is not valid or expired

    break;
  }
}

If Drupal 7: http://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_prepare/7

function YOUR-MODULE-NAME_node_prepare($node) {
    // Add PHP Code here to validate the hash code
    // You can use an if/else condition to print an access denied message
    // if the code is not valid or expired
}

And that is all.


Alternatives to Nodequeue? Are there any other modules that can implement the same functionality as Nodequeues i.e, making a customized list of selected nodes? I think I might be having some problems which might be related to it's permissions (I'm not sure of it as I'm still novice at Drupal). Maybe it's because it is still in beta phase for D7, I don't know...

All about that matter here.

Current options are:

Outline Designer
Weight
Nodeorder
Nodequeue
DraggableViews
Flag Weights
Sortable Grid Views Plugin
JQGRID


using sass to generate RTL & LTR css files in Omega 4 is there any convenient way of using Omega 4 to compile rtl and ltr css files automatically. I mean something like this or this, but for drupal.

I guess it depends on what you define as being convenient.

The SASS part is easy, since sass support is already setup in Omega. You just need to setup some sort of a sass structure to write the CSS.

To change the language settings, you'll want to invoke the template_preprocess_html() function to override the html that's rendered.
function template_preprocess_html


How to set a url in drupal database or settings.php? I had created a controller in  custom module using drupal 8.

 public function subscribe(Request $request) {

        $url='https://username:password@someurl.com/v1/subscriptions';

}

I am using git for development. This url is actually for Razorpay subscriptions. These url might get changed according to the mode in razorpay. So the url subscriptions in razorpay for test mode and live mode is different. I have to change url every time in this custom module while managing git.  Can I define this"$url" somewhere in backend in db or settings.php?

In your settings file add

$settings['razorpayUrl'] = 'https://example.com';

Then in your module

use Drupal\Core\Site\Settings;
$url = Settings::get('razorpayUrl');


Show 404 on page for node path url instead of redirecting to it's alias I'm currently using the Redirect module in Drupal 8 along with Pathauto to create aliases on all url's.  So for example /node/23 would be /article/some-text-here.  When a user types in /node/23 in the url it automatically redirects them to the alias url.  I want to show a 404 whenever the user uses the node path url instead of redirecting that way they don't ever have a chance to find something they shouldn't by traversing through my site with that pattern.

Make sure apache mod_alias is enabled and create a rule in .htaccess like:

Redirect 404 /node/.*$


Running multiple Drupal installations on one URL: is it advisable? My employer is considering replacing our fairly static website with Drupal, mainly so we can more easily implement a few ideas we've had, and also as a way of future-proofing it. It's something of an umbrella organization in that it has a few different customer-facing departments which aren't really related to each other, apart from falling under the same organization.

So, broadly speaking, each department has pretty specific needs - certain types of defined users, types of nodes; some require their own little forums, basic shopping carts, etc. My first instinct is to treat each department as its own Drupal installation with its own specific configuration of modules and keep things separate in that way. That said, there might need to be some functionality that spreads across the entire site. For example, one or two more senior members of staff might need to be able to log in and edit content across a few of the departments.

Is it possible to do this? To run different installations at domainname.org/dept1, domainname.org/dept2, domainname.org/dept3, etc. More importantly, is it advisable? What issues would I be likely to face if I were to go ahead with a setup like this?

Not only is it not a problem but it's actually a quite common practice!

Check out this link for some tips: multisite howtos

The only suggestion I have is to give each site a subdomain rather than a subfolder, in my experience this works a lot better:

dept1.domainname.org
dept2.domainname.org
dept3.domainname.org

(with all 3 hosts pointing to the same directory)

Setup

To set this up, just add a separate configuration folder under sites for each one:

/sites/dept1.domainname.org/setings.php // dept1 production
/sites/dept1.stagingdomain.org/setings.php // dept1 staging
/sites/dept1.domainname.local/setings.php // dept1 development
and so on...

Also, you should have separate files directories for each site and you can place site-specific (custom) modules on a modules subdirectory under the respective site's settings folder, to keep the /sites/all/modules directory uncluttered!


Is there any way to show user profile of authenticated user after loged in? I would like to have a block that contains basic profile of authenticated user so that they can see their username, photo, email and log out link.

Any help will be appreciated.

You can use Author Pane module to display a block of user information.

  Author Pane is a block of information about a given user, like those
  typically found on a forum post, but can be used in other places as
  well. From core, it collects the user picture, name, join date, online
  status, contact link, and profile information. In addition, any module
  or theme can feed it more information via the preprocess system. All
  of this information is then gathered and displayed using a template
  file.

If you do not want to use this module, then you can create a views to display user information.

Go to Administration -> Structure -> Views
Click on "Add new view" link
Set name for views in "View name" field and select "users" from "show" drop down.
Click on "Continue and Edit" button
Create a block display for the views.
Add "User: Picture", "User: E-mail", "User: Name" and "Global: Custom text (Custom text)".
Check check-box "Output this field as a link" under "Rewrite results" section for "Global: Custom text" and set "user/logout" as Link path for the field.
Save the views


How to set time limit only for one php file? I have a script which walks through database table, makes some checks and based on them it makes notifications for website users. It works for a pretty long time. Currently in dev it takes a minute for every user.  So I think I need to set max execution time(.htaccess, php etc) to 0 for this one.

Currently it's launched from "drupal page with form", later I'll be launching it with cron. Drupal is not letting me set set_time_limit(0) because it's not the beginning of file where I can put it. But I don't want to set_time_limit(0) for whole website.

Is there a way bypass this limitaion? Maybe some external script execution? I'd like to remain Drupal functionality in it.

Don't do this. While it is possible to do this, using set_time_limit(0) is giving your server free rein to execute indefinitely; you're setting yourself up for server instability.

If you have a large workload that you need to execute in a Drupal context, use its Queue API. This API will let you queue up a list of items to process (i.e. the table rows you're checking) and process them with a queue worker (i.e. the task that "does the checks" and generates user notifications).

You can find many examples of creating a queue and a queue worker by searching Google for [drupal 8 queue api].


Creation of entity with image field I would like to generate an entity that contains image generated by another module file in drupal 7. This is my code :

//appel de la variable user
global $user;

//recuperation de lapercu
$apercu = $_SESSION['image_generate'];
//creation de lobject file
$file_apercu = new StdClass();
$file_apercu->uid = $user->uid;
$file_apercu->uri = $apercu;
$file_apercu->filemime = file_get_mimetype($file_apercu->uri);
$file_apercu->status = 1;
//sauvegarde en base
$file_apercu = file_save($file_apercu);
$file_apercu = (array) $file_apercu;
$file_apercu = array($file_apercu);

//recuperation du pdf
$pdf = $_SESSION['pdf']->uri;
//creation de lobject file
$file_pdf = new StdClass();
$file_pdf->uid = $user->uid;
$file_pdf->uri = $pdf;
$file_pdf->filemime = file_get_mimetype($file_pdf->uri);
$file_pdf->status = 1;
//sauvegarde en base
$file_pdf = file_save($file_pdf);
$file_pdf = (array) $file_pdf;
$file_pdf = array($file_pdf);

//recuperation du numero de commande
$form_panier = $_SESSION['form_state_panier'];
$sql = db_query('SELECT MAX("order_id")
                FROM commerce_order
                WHERE uid = '.$user->uid.'')->fetchAssoc();

//creation de lentity
$values = array(
            'type' => 'commandeflyer',
            'uid' => intval($user->uid),
            'status' => 1,
            'comment' => 0,
            'promote' => 0,
        );

$entity = entity_create('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->title->set('commandeflyer'.$sql['MAX("order_id")']);
$ewrapper->field_flyer_image_commande->set($file_apercu);
$ewrapper->field_pdf->set($file_pdf);
$ewrapper->field_numcommande->set(intval($sql['MAX("order_id")']));
$ewrapper->save(true);
entity_save('node', $entity);

When I run this code I get this error :

EntityMetadataWrapperException : Invalid data value given. Be sure it matches the required data type and format. dans EntityMetadataWrapper->set() (ligne 122 dans /var/www/commerce_kickstart-7.x-2.9/profiles/commerce_kickstart/modules/contrib/entity/includes/entity.wrapper.inc).

But my type correspond : pdf for pdf and jpg for image. Thank you for help.

Solution found :

//appel de la variable user
global $user;

//recuperation de lapercu
$apercu = $_SESSION['image_generate'];
//creation de lobject file
$file_apercu = new StdClass();
$file_apercu->uid = $user->uid;
$file_apercu->uri = $apercu;
$file_apercu->filename = basename($file_apercu->uri);
$file_apercu->filemime = file_get_mimetype($file_apercu->uri);
$file_apercu->status = 1;
//sauvegarde en base
$file_apercu = file_save($file_apercu);

//recuperation du pdf
$pdf = $_SESSION['pdf']->uri;
//creation de lobject file
$file_pdf = new StdClass();
$file_pdf->uid = $user->uid;
$file_pdf->uri = $pdf;
$file_pdf->filename = basename($file_pdf->uri);
$file_pdf->filemime = file_get_mimetype($file_pdf->uri);
$file_pdf->status = 1;
//sauvegarde en base
$file_pdf = file_save($file_pdf);

//recuperation du numero de commande
$form_panier = $_SESSION['form_state_panier'];
$sql = db_query('SELECT MAX("order_id")
                FROM commerce_order
                WHERE uid = '.$user->uid.'')->fetchAssoc();

//creation de lentity
$values = array(
            'type' => 'commandeflyer',
            'uid' => intval($user->uid),
            'status' => 1,
            'comment' => 0,
            'promote' => 0,
        );

//creation dentity sans limage et le pdf
$entity = entity_create('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->title->set('commandeflyer'.$sql['MAX("order_id")']);
$ewrapper->field_numcommande->set(intval($sql['MAX("order_id")']));
$ewrapper->save(true);
entity_save('node', $entity);

//chargement de lentity
$commandeflyer = node_load($nid = $entity->nid, $vid = NULL, $reset = FALSE);

//ajout image
$commandeflyer->field_flyer_image_commande[LANGUAGE_NONE][] = array(
    'fid' => $file_apercu->fid,
    'uid' => $file_apercu->uid,
    'uri' => $file_apercu->uri,
    'filename' => $file_apercu->filename,
    'filemime' => $file_apercu->filemime,
    'status' => $file_apercu->status
    );

//ajout pdf
$commandeflyer->field_pdf[LANGUAGE_NONE][] = array(
    'fid' => $file_pdf->fid,
    'display' => '1',
    'uid' => $file_pdf->uid,
    'uri' => $file_pdf->uri,
    'filename' => $file_pdf->filename,
    'filemime' => $file_pdf->filemime,
    'status' => $file_pdf->status
    );

//save entity
node_save($commandeflyer);


Change node field with a comment I'm creating an issue tracking system with Drupal 7.

I have a content type called "Issue". in it there is a field "Assign To" that is a user reference field.

When a client create the issue he can specify the user that should handle it.

But when a client ads a comment to an issue, he sometimes want to change the assigned user.
Currently the only way to do it is by adding the comment, saving and the editing the issue, changing the "Assign To" field and saving.

I would like to make the "Assign To" (and the "Status") field available in the comment or as a separate component in the page.

Where should I start?

I found the following module that does a great job: Comment Node Edit.

  Gives Site Administrators ability to mark field instances as "editable
  by comment." When a field is editable by comment, the field will show
  up in the "add comment" form.


Using twig inside theme folder rather than twig from modules I installed a paragraph module and it uses twig from inside /modules/paragraphs/templates/
but I would like to override it inside my /theme/theme_name/ folder.

How can I do this?
Thanks.

Edit:

<!-- FILE NAME SUGGESTIONS:
* paragraph--steps--default.html.twig
* paragraph--steps.html.twig
* paragraph--default.html.twig
x paragraph.html.twig
-->
<!-- BEGIN OUTPUT from 'modules/paragraphs/templates/paragraph.html.twig' -->

Twig debug looks for the file in modules/paragraphs/templates and I would need it to look in mytheme/templates/. :/

Create templates folder inside your theme and enable Twig debugging, check here for how to enable twig debugging.

Once twig debugging enable look for theme suggestions and name the templates accordingly.


Functional test not displaying context aware block I have a context aware block I've created.

/**
 * Provide a context aware block.
 *
 * @Block(
 *   id = "my_context_aware_block",
 *   admin_label = @Translation("My context aware block"),
 *   category = @Translation("Display some node information"),
 *   context = {
 *     "node" = @ContextDefinition(
 *       "entity:node",
 *       label = @Translation("Current Node")
 *     )
 *   }
 * )
 */

It references the current node in the build method.

$node = $this->getContextValue('node');

Everything works as expected in my "live" environment. The issue I am encountering is that my functional test is NOT displaying the block when it IS in a context in which it should show. (I haven't bothered testing a context in which the block is not supposed to show.)

  public function testSomeStuff() {
    // Create a piece of content
    $node = $this->drupalCreateNode(array(
      'title' => t('My sample node'),
      'type' => 'a_valid_node_type',
    ));
    $node->save();

    // Place the block in the sidebar
    $this->drupalPlaceBlock('my_context_aware_block');

    $this->drupalGet('node/' . $node->id());

    // Note: Whether I check the page content or the response, I don't see
    //       the block there. I am showing examples of both just for the
    //       sake of providing detail in this question.
    $this->assertContains('force phpunit to fail so that I can manually look at the text content', $this->getTextContent());
    $this->assertSession()->responseContains('some valid markup that appears in the block');
  }

I have even tested setting

protected $profile = 'standard';

and the block still doesn't appear when I'm viewing the node I created [$this->drupalGet('node/' . $node->id());].

This is on Drupal 8.2.5.

I am inside of /drupal/root/directory/core running PHPUnit from the command line as such

sudo -u www-data ../vendor/bin/phpunit ../modules/custom/my_module/tests/src/Functional/MyFunctionalTest.php

Have I discovered a bug or is there something I am missing and doing wrong?

Edit: Here are more details of the complete solution.

First off, you will need to create a user that has administrative rights and log that user in to the site.

$adminUser = $this->drupalCreateUser(array(
  'administer blocks',
  'access administration pages',
));
$this->drupalLogin($adminUser);

Then, instead of using $this->drupalPlaceBlock('my_context_aware_block');, do the following:

// Place the block in the content area
$block_url = 'admin/structure/block/add/my_context_aware_block/classy';
$edit = [
  'region' => 'content',
];
$this->drupalPostForm($block_url, $edit, 'Save block');

Note: My block didn't need any context configuration. If it did, I could have included that with the $edit array.

As discussed in IRC, pretty sure your problem is $this->drupalPlaceBlock('my_context_aware_block'); which doesn't configure the necessary context mapping. That's not visible in the UI if you only have a single context, but it's still there and then stored in the settings.

See \Drupal\block\Tests\BlockUiTest::testContextAwareBlocks(), go to a URL like admin/structure/block/add/test_context_aware/classy, and save the block.
,


Deciding which field should be on Product node and which on product variations I'm wondering if I'm implementing my products the right way.

As I understand it should be the following.

I have different product variations with each their specific fields and SKU.
For example storage = 8 GB or 16GB

Then I have the main product to which these variations belong with main attributes such as the product name or compatibility. These are shared over the different variations.

So I consider I have my product nodes (or product displays?) with al my product information that is the same over the variations.
And I have my product variations with the SKU's and fields that are specific to each variation of the main product.

For me personally I think this is the correct way because you don't have duplicate data in your database. And if some field data needs to change, if it's a product specific field and not variation specific, you don't need to edit it over all the variation entities.

But I'm not sure that this is the correct way to do this according to standards, advise, other things I'm missing, ... . Because I'm very new to drupal commerce.

I think you're on the right track. If I'm not mistaken, a product display could be something like "Tee Shirt". The product variants would then be something like color or size. It's the same product with the core information, but the variants would be what ever is different, be it storage size or any other kind of variation from the original.

Edit: The product display can display any products. The variants are dependent on the actual product but the display can show anything.


paragraph template suggestion based on parent content type I have two content type using same paragraph as field , though template code will be according to content type. How can i can have different template names for paragraph template depending on content type.

Current naming convention: paragraph--paragraph-type.html.twig

Desired naming convention: paragraph--parent-content-type--paragraph-type.html.twig

Another solution will be get the url and pass it as variable in template and use template code according to url passed.

Add a theme name suggestion:

mytheme.theme:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function mytheme_theme_suggestions_paragraph_alter(&$suggestions, $variables) {
  $paragraph = $variables['elements']['#paragraph'];
  $parent = $paragraph->getParentEntity();
  if ($parent) {
    $suggestions[] = 'paragraph__' . $parent->bundle() . '__' .  $paragraph->bundle();
  }
}


filefiles node and comment in one view I have a content type called "Document" where i have a "file" field so i can upload files. I also have comments enable where another users can add a comment and also upload more files.

Whats i would like to do is have a table of all uploaded file in a single table at the bottom of the node.

In Views i am unable to get files upload from the node and comments in one views. Can anyone help with this?

using Drupal 7

Thanks

On the view that you have the files upload, under Advanced, add a relationship of comments of the node, then add Comment:Comment as a field.


Import CSV, converting repetitive fields to taxonomy terms Let's say I have a CSV file like this:

NAME, TYPE, COLOR
apple, fruit, green
banana, fruit, yellow
kiwi, fruit, brown
carrot, vegetable, orange
potato, vegetable, brown

You get the idea. Is it possible to import this CSV file such that specified fields (in this case TYPE and COLOR) are taxonomies, and new taxonomy terms are created automatically?

I really want to do this in Drupal 8, but perhaps a method would be to do it in Drupal 7 and then migrate the data.

It's not clear whether you're looking for a front-end tool, or help with implementing this using the migration APIs. If the latter, in Drupal 8 you can use the migrate_source_csv source plugin with the entity_generate process plugin provided in migrate_plus. Your migration YAML file might look something like

id: food
label: 'Import food nodes'
source:
  plugin: csv
  path: directory/my_csv_file.csv
  header_row_count: 1
  keys:
    - NAME
process:
  type:
    plugin: default_value
    default_value: food
  title: NAME
  field_type:
    plugin: entity_generate
    source: TYPE
  field_color:
    plugin: entity_generate
    source: COLOR
destination:
  plugin: 'entity:node'

The entity_generate plugin will lookup the incoming value in the appropriate vocabulary, create it if it doesn't already exist, and return a reference to the (possibly new) term.


cache a rest server index request I created one custom module for rest server, i created own resources and i want to be able to cache index request, for return a 304 with using http request if - headers.

I cannot find information on how to do it.

I did it setting my own headers (cache-control, last-modified, etag, expires), and setting rules for delete cache.


3 domain names for one instance of Drupal 8 We are currently developing a website on Drupal 8.

This site will be 3 versions . The difference between each site is minimal :

Different logo
Different colors CSS ( HTML structure remains the same ) .
Some content is filtered according to the domain name . For this, we created a selection field in the content type to know on which domain name the content appears (checkbox  Site A , checkbox Site B,checkbox  Site C. A content may appear in several versions , the choice is multiple)

Our question is : what is the best way manage this type of project with Drupal 8 ? We are aware that this could cause problems at the Drupal cache if we do a simple detection via preprocess to load a particular CSS or content.

I am doing something very similar to migrate some D5, D6 and D7 sites to one D8 site.
Currently I have this solution:

(1) Have one master domain that serves all content (i.e. proreos.de).

(2) Have some paths (routes) that serve special content for different domains (i.e. /asde/* -> serve content for anwalt-seiten.de/*)

(3) Have ThemeNegotiatiors (ThemeNegotiatorInterface) watching for that special routes to set the 'other' theme (like asde-theme).

(4) Have inverse proxies (apache2 mod_proxy) on the "other" domains that deliver the subcontent from the master domain (i.e. anwalt-seiten.de/index.html -> proreos.de/asde/index.html)

The advantage I hope to have from this approach:

(a) Have all data in one place (proreos)

(b) Have presentation separated from model (special themes)

(c) Have scalability (by inverse proxies).

But I don't have real experience cause I am still developing. Hope it helps anyway.


What hook can I use to modify Views Datasource JSON output? I'm using Views and Views Datasource to generate a JSON feed for my site. I've got a Video field which has both a video and a thumbnail image.

I want to include the url of the thumbnail image in my json feed. I add the Video field to my list of fields in the View and I choose the "Video thumbnail" format instead of the "Video Player" format so that it will show the thumbnail instead of the video. When I do this in a normal View it works perfectly. However, when I do it with a JSON document view, it doesn't work properly. It renders the url to the video instead of rendering the url to the thumbnail image.

I'm going to create another question which talks about how to get this to work properly, but THIS question is my backup solution.

I can rewrite the field so that it includes the fid of the thumbnail image, so my current idea is implementing a hook that will allow me to post process the rendered json or manipulate the data structure before it gets converted to json so that I can just lookup the image by its fid and then replace that piece of data in the array with the proper image url.

I have tried MANY hooks so far, but none of them provide data which represents the json data.

hook_views_pre_view
hook_views_pre_render
hook_views_post_render
hook_views_post_execute

My guess is that Views Datasource is processing the data after I've seen it in my hook implementations.

What hook can I use so manipulate the data structure before it gets converted to json or alternatively, what hook can I use to manipulate the json string after it has been converted to json?

I find my 1st answer informative regarding auxillery information regarding views and views_datasource. So here's 1 way I think you get the url you want.

You said:

  My guess is that Views Datasource is processing the data after I've
  seen it in my hook implementations.

It is, look at what views_json_view_pre_render() is doing:

function views_json_views_pre_render(&$view) {
  if(isset($view->plugin_name) && $view->plugin_name == 'views_json') {
    // Support for Video field.
    if(!empty($view->result)) {
      // Process each View result.
      foreach($view->result as $row => $result) {
        // Only process the entity fields defined by the View.
        foreach($view->field as $field_name => $field) {
          if($field instanceof views_handler_field_field) {
            if($field->field_info['type'] == 'video') {

              // Get the Video URL.
              $video = $field->get_value($view->result[$row]);
              // -- See this line !!
              $url = file_create_url($video[0]['uri']);
              $render_array = array(
                '#type' => 'markup',
                '#markup' => filter_xss($url),
              );
              // Substitute embed code with URL. @todo Add support for escaped embed codes.
              // See this line !!
              $view->result[$row]->{'field_'. $field_name}[0]['rendered'] = $render_array;
            }

If its a video field views_json is taking each of the results and replacing the embed code with the URL of the video. This is what  you're seeing.

So how do you fix this. You write your own hook_views_pre_render() that runs before views_json's pre render. In your pre render function you change $video[0]['uri'] to whatever url you want -- ultimately thats the value views_json will use. If you can get the FID or the full url to the image here you should be able to easily set that value.

So in your own module you'd write 2 functions:

// File: mymodule.install
function MYMODULE_install() {
// Set the weight of the mymodule.module to a value lower than views_datasource's views_json module.
  db_update('system')
   ->fields(array('weight' => -1))
   ->condition('name', 'mymodule')
   ->execute();
}

// File: mymodule.module
/**
 * Implements hook_views_pre_render().
 */
function mymodule_views_pre_render(&$view) {
  if(isset($view->plugin_name) && $view->plugin_name == 'views_json' && $view->name == 'YOUR_SPECIFIC_VIEW') {
    // Support for Video field.
    if(!empty($view->result)) {
      // Process each View result.
      foreach($view->result as $row => $result) {
        // Only process the entity fields defined by the View.
        foreach($view->field as $field_name => $field) {
          if($field instanceof views_handler_field_field) {
            if($field->field_info['type'] == 'video') {
              // Change the video uri to the image you want ...
              $view->result[$row][0]['uri'] = /* some logic here */;
            }
          }
        }
      }
    }
  }
}

Your pre render hook will run before views_datasource's. It simply alters the url to whatever you want. Then views_datasource's views_json hook runs and just uses it as its supposed to -- you just slipped in the correct value. This should work. Code is untested.


Content profile + rules. Problem with action, when user is created a profile then logged in guys. Got a problem with content_profile and rules modules. By default rules has a

  Redirect to profile creation page, if users have no profile.

It works fine. When a user is registering on the site then logging in, it redirects the registered user to a node/add/profile (Content profile creation page). But when a user that already has a profile node logs in, he's redirecting to mysite.com/node, not on a user page.

What's wrong?

Where do you want them to go?

  Redirect to profile creation page, if users have no profile.

If a user already has a profile node, they won't be directed to create one (as stated in the rule itself) so when the user logs in, he/she should be taken to your default front page (or whatever page he/she was trying to access if access was denied to anonymous users.

EDIT

If you want users to be directed to the user page if they already have a profile, simply create another rule to do so.  Below is an example of a rule to do this for you:

Create a new rule, give it any title you like, for the Event select User has logged in and click "Save changes"
Now click "Add a condition", choose User has content profile and click the "Next" button
On the settings page for the condition, you may choose what content type to use for your content profile condition.  Choose one (or leave it if using default Profile) and click "Save"
Now click "Add an action", choose Page redirect (under the System heading) and click the "Next" button
On the settings page for the redirect, in the first textbox for To: enter user,  click the "Force redirect" checkbox and click "Save" (as seen below):

Make sure the rule is enabled and your users should be directed to the correct pages.


Drupal private file system and possible sharing options I have issues setting file system (private) for users as described here. I wonder what they ment by

"This setting is used as the preferred download method. The use of public files is more efficient, but does not provide any access control."

If i want let only user that uploaded file have access to the file, which setting should i choose, and what are drawbacks?

Moreover, could if i choose private system, could i control access by module (for exaple User relationships module, so the friends of user could download the file)

Thanks.

Private filesystem allows Drupal to run permission checks before serving the requested file.

If you are using public file system, direct links to your files will be accessible to anyone, no matter they are logged in users or anonymous.

Regarding your questions:

  If i want let only user that uploaded file have access to the file, which setting should i choose, and what are drawbacks?

You should choose private filesystem. Drawbacks are explained above.

  Moreover, could if i choose private system, could i control access by module (for exaple User relationships module, so the friends of user could download the file)

Check out hook_file_download() - you can use it in a custom module to perform custom access checks.

Also, see this thread.


Site architecture - consistent paths, breadcrumb and menu We've been trying to implement a site architecture that has a consistent menu, breadcrumb and path structure for all pages in the site.

This is easy for basic pages since the path can be set using the page's menu position (using pathauto), as can the breadcrumb.

eg: site.com/a-page/b-page

However, we also have 'articles' which appear in lists on certain pages, using certain tags.

The issue comes in preserving the consistent menu location (but no menu item), URL and breadcrumb for these articles whilst keeping the system easy to maintain.

eg: site.com/a-page/b-page/article-1
eg: site.com/a-page/b-page/article-2

(Most Drupal sites seem to just give up and use site.com/article-title ?)

Not all the articles are just 'news' so we don't want to just force the path to one format option using pathauto.

One solution we've identified for these articles is:

Add a field to the taxonomy for 'path to parent' which would contain the path to whatever page the articles are listed on (eg: a-page/b-page/) and then pathauto could then use this to build a relevant path to the content. Then create a Context for each term which sets the Breadcrumb and Menu trail to the correct location.

However, this does not seem very easy to maintain?

Does anyone know of a better solution?

I think instead of using Article content type, you should use Book content type.
so you could create a book page named a-page, then a page named b-page and provide it a-page as parent in options below.
Now start adding article-1 and article-2 as child of b-page.

So when you view these pages article-1 or 2 the breadcrumb and will provide the url as site.com/a-page/b-page/article-1

Correct me if i misunderstood the question and do tick right if the answer is right.


Is it a bad practice to use dynamically generated IDs for theming Is it a bad practice to have styles such as these in the css files ?

#block-block-1, #block-block-7, #block-block-8

I mean, if one was to delete the block and recreate it the styles would no longer be valid.

Or is it best to modify the template and target the selectors in the template ?

It is better not to use the id.

You could use this module Block Class which allows you to add a class to the block and you can then style your css using that class.


Can you create a tpl based on view page url? (Drupal 7) There's a view page which takes in taxonomy terms to display related content topic/Easter, where Easter is the term. Now in this example, I would like to create a separate TPL for that page topic/Easter. Is that possible?

You can use Taxonomy Views Integrator module. Create separate views for this taxonomy term page and set it. And You can create separate template for this views.

Or You can use hook_preprocess_views_view for creating views template for custom view and custom view display. For ex.

     function THEMENAME_preprocess_views_view(&$variables) {
      $view = $variables['view'];
      if($view->name == 'your_view_name' && $view->current_display == 'main_page')
   {
        $variables['theme_hook_suggestions'][] = 'views_view__viewname';
      }

Your template will be views-view--viewname.tpl.php in this case


Rules link get url parameters I've got a rule link in a view
Rules link generates me this link per user displayed by the view

http://localhost/drupaltest/addequpier/18/14/6OwljLX8KLBfNPrW37bzulzuue25VJmkzWtGiPmR-mc

18 is the user id
14 the node id (i've added this parameter with rewrite url)

How can get those parameters from the url with rules ? Do i have to rewrite the url ?

I'm using Drupal 7

I've resolved my problem finaly, I think there was a conflict with a Disabled module (Rules Forms).
I can set the displayed variables under "parameters" in my rule config.


Override front page to not display promoted article Is it possible to override front page template to not display the promoted articles? I am using the promote to front page option to filter the contents in a  view so I cannot uncheck it.

You can simply remove nodes attached to the front page in the preprocess.

/**
 * Implements template_preprocess_page()
 */
function THEME_preprocess_page(&$vars) {
  // Remove 'Promoted to front page' nodes
  if ($vars['is_front']) {
    unset($vars['page']['content']['system_main']['nodes']);
  }
}


What are the benefits of Views 3? I am exploring a reason to upgrade from Views 2x to 3x.

What major benefits Views 3x provides?
Are there any major API changes?

There are hundreds of improvements. There are also many API changes, but they would only affect custom code using Views hooks, not the views themselves, which are converted upon update.

Some major features:

Functionality similar to Semantic Views.
Group-by support and aggregate functions: you can do queries like "give me the count of nodes written by each user, sort by the amount of nodes DESC."
Views OR: you can separate different filter conditions by OR.
Pluggable pagers.
Pluggable exposed filters: expose items per page, sort.
Header, Footer, and Empty Text as pluggable areas.
Pluggable caching.
More argument, filter, and sort handlers.
Pluggable backends Flickr API, Apache Solr, RDF, etc.
Displays can now be disabled, renamed, and reordered, cloned.
A new UI in the Drupal 7 version.

Most importantly, it provides a much smoother upgrade to Views 7.x-3.x.

See the CHANGELOG.txt for a complete list of changes.


Form select option results in "Illegal Choice has been detected" I have a form where a user picks a date for their submission(s) to appear on the website. I am populating a 'date' field like so:

function mymodule_get_date_options($type = 'start') {
  $options = array();

  $start_week = time();

  if (date('w', $start_week) == 3) {
    $start_week = strtotime('+1 week', $start_week);
  }

  while (date('w', $start_week) != 3) {
    $start_week = strtotime('+1 day', $start_week);
  }

  if ($type == 'end') {
    $start_week = strtotime('+1 week', $start_week);
  }

  for ($x = 0; $x < 24; $x++) {
    $options[date('U', $start_week)] = date('M d, Y', $start_week);
    $start_week = strtotime('+1 week', $start_week);
  }

  return $options;
}

And the element:

$form['start_date'] = array(
    '#title' => t('Start Date'),
    '#type' => 'select',
    '#options' => mymodule_get_date_options('start'),
    '#default_value' => $mymodule_form_object->start_date,
  );

The generated HTML:

// a chunk of the option elements
<option value="1313615248">Aug 17, 2011</option>
<option value="1314220048">Aug 24, 2011</option>
<option value="1314824848">Aug 31, 2011</option>
<option value="1315429648">Sep 07, 2011</option>
<option value="1316034448">Sep 14, 2011</option>
<option value="1316639248">Sep 21, 2011</option>
<option value="1317244048">Sep 28, 2011</option>
<option value="1317848848">Oct 05, 2011</option>
<option value="1318453648">Oct 12, 2011</option>

So, everything looks okay, except when the form is submitted it says 'An Illegal Choice has been detected" with the date selects highlighted.

That's because the form gets generated both upon output and submission, and you're using form values that are time-dependent. When you first output the form it generates options like this:

1313615248
1314220048
1314824848
1315429648

And when a user submits the form, it will generate new values, with a few second difference:

1313615268
1314220068
1314824868
1315429668
(+20 second difference)

So none of the previous options are present here. Drupal's validator by default checks if the submitted option is among generated options.


Nodes being imported from the Feed module not being published I have finally accomplished the communication between my 2 websites through the Feed module. I am exporting xml and I am using the XPath XML Parser to receive the nodes. The problem that I have now is that it is only updating nodes that have been previously imported through the feed, even though some of that content was already on the other website. The ones that are being imported are left with the Unpublished status, even though they were initially published on the website that exported them. How can I change this?

I know this might sound way too easy but have you been into the content type you are importing to and made sure that it is set to default published? Unless you tell the imported nodes otherwise, they will use the default for the content type. If you are using the published status from the xml as the published status for the imported nodes, then thats another matter.


How to theme form elements in a custom field widget? I'm creating a custom telephone field and I'm a bit confused at how to go about theming the widget.

I have four elements in my implementation of hook_field_widget_form()...

A dropdown for the phone type, (i.e - phone, fax, toll-free).
A textfield for the phone number.
A textfield for the extension with the prefix "ext".
A checkbox to flag the number as the primary number, (the field has unlimited cardinality).

Functionally, the field is working great. It is saving the data in the database just how I would like. What I'm not figuring out is how to display the elements inline on the edit form. Right now, the form for the field looks like this...

I would like each of the elements to display inline. If I could just add a class to the div that wraps each of the elements, I'd be good to go. The closest that I've come is to add a class in my implementation of hook_field_widget_form() to each of the elements, but that adds it to the element and not the wrapper div.

I have a feeling I'm going to need to implement a theme function or a template file, but I just don't know where to start. All the information that I find about theme functions and template files seem to be about what the elements look like rendered on the page, and not about what the form elements look like on the edit form. I know that the theme function that builds the form element is 'theme_form_element', but if I alter that, it alters all the form elements. I'm not sure how to target just the elements in my module or if this is even the route to go down.

Can someone please point me in the right direction? I have been stuck on this for days.

UPDATE 01Nov14

It's been a few days since I posted this question, and I'm still very stuck. Here's another screenshot that may be able to clear up what I'd like to do. How do I add a class in the wrapper divs pointed out in this screenshot?

To add class to wrapper div of a form item you have to use the following theme function : theme_form_element

Copy and paste the entire theme_form_element function and rename the function with mytheme_form_element in your template.php and add your custom code like this (you may adjust to your own id) :

/* CUSTOM */
if (module_exists('mymodule')) {
  if (isset($element['#id']) && ($element['#id'] == 'phone' || $element['#id'] == 'ext' || $element['#id'] == 'primary')) {
    $attributes['class'][] = 'my-class';
  }
}
/* END CUSTOM */

It's always difficult to change the structure of forms because it's in theme function and for that you have to add conditions.


I'm trying to create two content types at once in one form. One is a parent page the other a child page So I'm workoing on a story archive website and I've created several interations using the Book module in drupal. However while I like all the stuff book does by default I need to streamline the process of content creation and I'm no longer sure I can do that easily with book module.

I am right now trying to figure out how to create a way to create both the front page and the first child page of a story/book in the system, and create an easier way to add a chapter to a story and tell drupal what the chapter number is. If anyone has any advice on this I would appreciate it emensly.

The Inline entity form module was built for pretty much that exact use case:

  Provides a widget for inline management (creation, modification, removal) of referenced entities.

  The primary use case is the parent -> children one (product display -> products, order -> line items, etc.), where the child entities are never managed outside the parent form.

  Existing entities can also be referenced.


Panels is still adding sidebars Here is what we are doing:

We are working to build a new theme for the website we are working on.
We are using ThemeKey and Context to utilize the areas of the new given content types / drupal paths we are using for the new theme instead of Panels.
Panels previously owned the pages we are building on.

For Some Reason, sidebars/blocks (from the previous panel) is still printing to the $content tag for the new theme.

Any Ideas?  It's somewhat hard to describe the behavior over this platform, if you ask questions, I promise to answer them quickly until the problem is resolved...

I inherited this site.

In the Panels Page Manager, rules were set up for "node/#."
Therefore, any new node was printing blocks as a sidebar because of those set rules. I reconfigured those rules, and the problem has been fixed.


How do I import using features? I have a drupal site and I exported a Drupal feature and got a download file. Now I want to import that file to another drupal site, but there is no import function, so how do I add it?

You just need to copy this folder generated by Features into your /sites/all/modules/features directory. A feature is a module, you'll need to enable this feature on your new site to retrieve all the functionnalities.

You'll probably need to take a close look at the documentation for Drupal 7 https://www.drupal.org/docs/7/modules/features to achieve this correctly.


Active main menu link I need to set an item in the main menu as active even though I'm using separate sub menu blocks. What is the best way to do this? Due to particular styling I cannot just put them under the Category headings (like breadcrumbs).

The problem I came across is that the main menu item isn't active, as it doesn't know that the user is in the sub category of it as there is no link back. I can't find a way to set a particular main menu link as class active.

You should look into menu position. You can set active menu trails based on path or node type and they have a simple api for extending the functionality.


How Webprofiler EntityManagerWrapper overrides EntityTypeManager? In trying to understand the new paradigm of Dependency Injection, I attempted to install Webprofiler into my D8.6.10 project but it seemed it causes a conflict with my already installed fullcalendar_view. It has a dependency that is expecting an instance of Drupal\Core\Entity\EntityTypeManager which is important in this new world to declare what is required for your class/method to work.

Stepping through the stacktrace, at some point Drupal is aware that the fullcalendar dependency is requiring EntityTypeManager but the call is co-opted by WebProfiler into EntityManagerWrapper and it breaks the site.
I could only get past it by removing the EntityTypeManager requirement. My frustration is that I'm trying to understand when I should pull this stunt to remove a requirement for things like Webprofiler and when I should not. I apologize that I don't have the means to ask a focused question because I don't have enough knowledge about this new paradigm yet.

Which is why I ask here.

Is it Webprofiler not respecting the fullcalendar_view requirement and invoking the EntityManagerWrapper or is the fullcalendar_view asking for the wrong requirement?

Yes, the module fullcalendar_view is probably asking for the wrong requirement. Services which implement an interface are supposed to be swappable with services implementing the same interface. So if the module has no reason to check for this specific class it should check for the interface EntityTypeManagerInterface instead.


What is the basic concept behind revisons in term of performance? On a Drupal 8 project, I am planning to allow revisions to be created for one "content type" which consist of around 40 different fields !

Can someone explain the concept behind on how Drupal save the revisions ?

My main concern is that the "Content type" in question will have in one year around "one million +" nodes with at least "3 revisions" for each node.

Could this affect the performance of the website ?

Revisions are treated as separated nodes as well ?

Update:

Any node of this content type will live on the website for a period of 1 year and then will be deleted for good !

Drupal essentially stores a copy of the node each time a revision is created. So if you're making alot of text edits it will be your database size that will mainly increase because of enabling revisions. (But drupal will also keep any files uploaded that are associated with previous revisions)

So normally for nodes you have about 3 core tables with a row for each node. Then you have a table for each field you add to content types e.g. "node__field_my_field" which holds the live content for that field.

So with a million nodes you'd expect 1 million rows in the core node tables and up to 1 million rows in each of your field tables for each node (If you populate every field for every node)

If you enable revisions a few new tables get created to start tracking each revision, I think its 2 extra core tables and then a revision table for each field. But this time every time you make a revision it add a row to all these tables. So with your 1 million nodes with 3 revisions you will effectively quadruple your database storage requirement

But in terms of site performance it shouldn't really have too much effect as databases can scale well


Call-time pass-by-reference has been deprecated in phptemplate_init() with specific theme I installed the last Drupal 7 Stack from BitNami. It seems to work correctly with the default themes but when I switch to the twitter_bootstrap theme (7.x-2.x-dev at http://drupal.org/project/twitter_bootstrap ) the "Call-time pass-by-reference has been deprecated in phptemplate_init()" appears.

I look at the phptemplate.engine file but can't pinpoint the issue at line 14 (_include_once DRUPAL_ROOT . '/' . $file;_)

<?php

/**
 * @file
 * Handles integration of PHP templates with the Drupal theme system.
 */

/**
 * Implements hook_init().
 */
function phptemplate_init($template) {
  $file = dirname($template->filename) . '/template.php';
  if (file_exists($file)) {
    include_once DRUPAL_ROOT . '/' . $file;
  }
}

/**
 * Implements hook_theme().
 */
function phptemplate_theme($existing, $type, $theme, $path) {
  $templates = drupal_find_theme_functions($existing, array($theme));
  $templates += drupal_find_theme_templates($existing, '.tpl.php', $path);
  return $templates;
}

The indications to solve this issue are available at: http://drupal.org/node/1423518


Overwrite login page I'm trying to overwrite the FULL LOGIN PAGE, not only the login form!

I've tried this

function your_themename_theme() {
  $items = array();
  // create custom user-login.tpl.php
  $items['user_login'] = array(
  'render element' => 'form',
  'path' => drupal_get_path('theme', 'your_themename') . '/templates',
  'template' => 'user-login',
  'preprocess functions' => array(
  'your_themename_preprocess_user_login'
  ),
 );
return $items;
}

and this:

function YOURTHEME_theme() {
  return array(
    'user_login' => array(
      'template' => 'user-login',
      'variables' => array('form' => NULL), ## you may remove this line in this case
    )
  );
}
function YOURTHEME_preprocess_user_login(&$variables) {
    $variables['form'] = drupal_build_form('user_login', user_login(array(),$form_state)); ## I have to build the user login myself.
}

but that's only working for my login form. I have a website with all same layout pages but only the login is different. How can I disable regions and edit css from my login page?

UPDATE:

Now I changed the name of the template to page--user--login.tpl and when I put
test
 in my the template I see test in my browser. But when I type nothing I see the login form but also my sidebar/footer. How can I remove them?

The normal method for creating a custom page--user--login.tpl.php is not to create an empty file, but to copy the  page.tpl.php supplied with the theme you're using into the templates/-directory of your sub-theme, rename it page--user--login.tpl.php, and edit the copy.

For instance, to remove the footer, just locate the markup in your copied page--user--login.tpl.php that is used to template the footer, and delete it!

  <?php if ($page['footer_firstcolumn'] || $page['footer_secondcolumn'] || $page['footer_thirdcolumn'] || $page['footer_fourthcolumn']): ?>

      <?php print render($page['footer_firstcolumn']); ?>
      <?php print render($page['footer_secondcolumn']); ?>
      <?php print render($page['footer_thirdcolumn']); ?>
      <?php print render($page['footer_fourthcolumn']); ?>

  <?php endif; ?>

  <?php if ($page['footer']): ?>

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

  <?php endif; ?>

The block above is an example of how this may look like (this is from a copy of Bartik), if you copy it from another theme, it may look different.

But to get rid of it, you pull it into your favourite text editor and delete all of it.


Update database with update module disabled I have recently inherited a site which needs protecting from the recent security exploits. The site has not been very well maintained but the hosting company can provide me with a database dump from 6th October.

Trouble is, the database dump has the update module disabled. When I try to restore the site and upgrade to the latest core version* I am prevented because updating is disabled.

Is there a way of enabling the update module via the database? I am pretty new to drush and do not yet have it enabled on the server.

*Actually it's an early version of Commerce Kickstart 2.

Doh. Update wasn't working for me because I didn't exist on the system. Silly mistake


content access does not work after changing domain after designing and developing a website I changed its domain. Now any of the permissions are not working. every thing is OK appearently but the functionality is not OK at all.(I mean all the checkboxes and settings are correct but anonymous users have access to all contents!!)

I am using content access module and check the  Enable per content node access control settings  option in content type setting.

Rebuild the permissions table.

Go to /admin/reports/status/rebuild
Or find the link on the status report: Reports -> Status report and the link is under the Node Access Permissions row.


How to remove files using File widget After clicking on the "Remove" button, the entry disappears, but the file is still on the server.

Managed files are deleted on cron run for D7.


Create content fields order How can i reorder fields in "node/add/"?

the current order:

title
vocabularies
body
...

i would like to have

    title
    body
    vocabularies

...

Drag and drop the fields in the order you want at page at the "manage fields" or "manage display" pages.

You can reach these pages for eacht content-type via the links beside eacht content type at:

admin/structure/types

Manage fields is used at the node/add or edit screens.
Manage display is used for the actual display, like when a visitors sees the page.


How to hide the "Add to cart message" on mobile site"? I'm using two different themes for main site and mobile site. I want to hide the Add to cart message on mobile site because I've created a custom window with custom messages but I want it to be displayed on the main desktop site. How can I hide it on mobile site?

One way to do it would be to use hook_node_submit to override the submit handler for commerce_cart_line_item_views_form_submit. Check for your theme and apply messages appropriately. However, that will only work for this single message. You would have to rewrite all of the cart functions that have messages.

Another way: I know you can do this with CSS. You just need to target the product pages only. I don't know your CSS structure, but if you look at the classes in the <body> element, you should see classes that you can use to cascade down and set display: none; to the message region. I don't know what other messages will show up that you care about on the product pages. If you do have some, then the first option is your only option. (Or the non-recommended option below.)

You could also edit the cart source but that is not a good option because it breaks your upgrade path.

If you are using Kickstart, I can find the function to override there as well. (I have sites running both.)


Empty taxonomy pages I  am having a taxonomy problem that I can't figure out and my searches haven't helped. Basically, I have created a taxonomy to tag my pages and I can use this field with views etc without any problem. However, when I have created links to those taxonomy terms, the page is coming up as empty (except the term is listed at the top).

If I use /all, then it seems to be working without problem.

So, this works: /taxonomy/term/all

this doesn't: /taxonomy/term/17 (though that term does exist)

this doesn't /taxonomy/term/17/all

In addition, I am using the taxonomy menu module. If I add a new term, it shows up in the menu, but if the counter is enabled, they all show up as "0."

(Drupal 6)

slowly going crazy....

Thanks

I believe this question is too broad to have a correct answer. As noted in the comments, there are a few ways that this symptom could occur (i.e. modules that intervene), and tools to diagnose further (e.g. the sql query tool).

For my money, your best bet is to first figure out what code is actually handling the url - you might be able to do that with some debug code, or else by inspecting the menu tables (which are also routing tables in Drupal 6).


How to show webform as block In drupal 7 we used to attach a webform to nodes and then we could render them as a block, nowadays in drupal 8 Webform is a dependent entity and is designed and developed on its own. now my question is :

  I've created a webform and now I want to place it in a block so user can simply fill it up in front page, How can I show a webform as a Block?

Special thanks to Peacog Web Development for their great tutorial .Here is the tip:

  Rather than Drupal 7, Different Block types can be created by admin

so the solution is simple :

Create a new block type using : admin/structure/block/block-content/types
Add a Reference of type Webform to custom block type
remove body if it's inappropriate
modify custom block Manage Display so the form would be rendered as webform
your new Block type is ready

now to add any new webform as block you, you will need to add new block of type Custom Block and refer to your webform, and that's done.


Show comment link function based on node comment settings and not user privilege I'm creating a custom theme and module for one of my content types. I want to show the comments link in a specific content type only if comments are turned on for the node or even globally for the content type specifically. I had originally used the following, simplified for example, in my tpl.php, which shows the link if the user has the privilege to comment. However, in my case, while I allow comments all over the site, I don't allow them on this particular content type. I want to leave the option open in case we do allow comments in the future.

<?php
 if (user_access('post comments')) {
  print 'Comment';
 }
?>

I was hoping that the system would recognize that a user that has privilege to comment every else still doesn't have privileges to comment on this node, and the link would not show, but it seems to show to anyone that has comment privileges, regardless of node.

What should replace user_access()?

If you look at https://api.drupal.org/api/drupal/modules%21node%21node.tpl.php/7.x

and click View source

and scroll down a bit, you will see that there is a variable that you can use:

  $comment: State of comment settings for the node.

So my guess would be that the value is either 1 (TRUE) or 0 (FALSE).

Using Devel module you can use Devel's dpm() function, so put:

dpm($comment);

to dump and see it's value.

If my guess is correct, then you would need to do something like this:

 if ($comment == 1) {
    print 'Comment';
 }


Why do I get "Command 'drupal-update' is not defined" when I run "composer drupal-update"? I'm using Drupal 8.2.7 on XAMPP, on Windows 10. I am installing AMP via Composer, but I received an error  when I run composer drupal-update.

I ran the command from the Drupal root folder.

  [Symfony\Component\Console\Exception\CommandNotFoundException]
      Command "drupal-update" is not defined.

What happened?

Neither Drupal core nor Composer define that command. It's the Composer Manager module that defines it.

Be sure to read carefully the instructions to properly install the module, and the following note the project page gives.

  Drupal 8

  The Drupal 8 version of this module is deprecated and no longer needed, due to improvements in Drupal 8.1. Use Composer directly to get the needed modules, which will also download their required libraries.

The installation instructions are the following.

  Installation

  Install the Composer Manager module.
  Run the module's init.php script on the command line
  (php scripts/init.php from inside the composer_manager module directory).
  This registers the module's Composer command for Drupal core.
  Run composer drupal-update from the root of your Drupal directory.

If you are wondering why you don't see the Drupal 8 version in the project page, that is because, as the project page says, the Drupal 8 version is deprecated. The last Drupal 8 version is 8.x-1.0-rc2, visible in the releases page.


How to anonymise user names and emails? The developer stages need their user names and email address anonymised. I did not find anything googling the subject matter. Maybe somebody developed a Drush extension for this? Any other suggestions are welcome too.

I came up with this:

drush sql-query "
  UPDATE users
  SET
    name=CONCAT('User-',uid),
    mail=CONCAT(uid,'@anon.com'),
    init=CONCAT(uid,'old@anon.com')
  WHERE uid > 0;"
drush upwd User-1 --password=SecureAdminPassword


Views Data Export Module not including the custom added rows in a view I have created a view for commerce orders where format is tabular and they are grouped by email of order owner. So basically each group of record shows how many orders are placed by a given email id.I need to have a extra row in each grouped results which is basically summary of order(showing cumulative order total) so I used views_summarize module and got it done. Now I need to have export views as csv or xls functionality so I put views_data_export module but it seems the row added by views_summarize is not included by csv or xls generated by views_data_export.

I also tried including the row using hook_views_pre_render(), and I am seeing the row is getting added in the views page under preview but when I export the views in csv again the row does not appear.

Here is code

function mymodulename_views_pre_render(&$view) // don't forget to replace my_module with your modules name
{
  if($view->name == "paid_partner") {
    if($view->current_display = "paid_partner_csv" || $view->current_display = "paid_partner_xls") {
      foreach($view->result as $submission) {
        $order_total_summary += $submission->field_data_commerce_order_total_commerce_order_total_amount;
        $quantity_total_summary += $submission->commerce_line_item_field_data_commerce_line_items_quantity;
        $currency = $submission->commerce_order_total_amount_currency_code;
      }
    $price_display = commerce_currency_format($order_total_summary, $currency);
    // insert a 'total' row
    $row = new stdClass();
    $row->order_id = "Order Summary";
    $row->users_commerce_order_mail = "Order Total Summary";
    $row->commerce_line_item_field_data_commerce_line_items_quantity = $quantity_total_summary;
    $row->field_commerce_order_total[0]['rendered'] = array(
      '#markup' => $price_display,
      '#access' => TRUE,
    );
    $view->result[] = $row;
    }
  }
}

What can I do to include the summary row with each grouped record in exported csv or xls.

Views Data Export does not render your results in a traditional way, so render hooks are not executed. But you should be able to alter results using hook_views_post_execute:

This hook is called right after the execute process. The query has been executed, but the pre_render() phase has not yet happened for handlers.
Adding output to the view can be accomplished by placing text on $view->attachment_before and $view->attachment_after. Altering the content can be achieved by editing the items of $view->result.

Emphasis mine - that's what you should to to alter content not only for display purposes, but in generic, usage-independent way.


I would like to split up the fields in the 'create new content' screen into sections I have a content type with about thirty different fields.  I would like to group them by category and I would also like to split them up so that half of the fields are filled in at the time of creation and the rest are filled in later (as a two-part work flow.)  There is a strong possibility that access to the two field groups will require two different roles.  Is there a good module that can do this?

You can use the Field Group module to group fields together.

You can use the Field Permissions module to only allow access to certain fields based on users roles.


Comet implementation Does anyone know how to implement comet in Drupal?
I saw a rudimentary PHP implementation on Stack Overflow.
Is there any module which does this?

As written in that answer, that is blocking a whole apache thread and therefore not a good idea.

I suggest you have a look at http://drupal.org/project/nodejs. node.js is an event-based webserver written in JavaScript and that is the module that integrates it with Drupal. Then, your clients keep a connection option with the node.js server and you can contact them through that server.

The project is still in development, I don't know how well it is working already.


What is the variable/method to address the content type in a template file? What is the variable/method to address/fetch a particular content type in template files?

What variable/method shall I put at the blank space so my statement/logic will be like if contentType == 'article'?

{% if ____________ %}
  ......
  ........
{% endif %}

call the getType method of the node object, like:
 node.getType() == 'article'


Why can't you assert the response status in a FunctionalJavascript test? If I do this in a FunctionalJavascript test:

    $assert_session->statusCodeEquals(200);

I get:

  Behat\Mink\Exception\UnsupportedDriverActionException: Status code is not available from Drupal\FunctionalJavascriptTests\DrupalSelenium2Driver

Why though?

This has a little history behind it.

Mink is the library that build on top of phpunit for functional testing:

  One of the most important parts in the web is a browser. A browser is the window through which web users interact with web applications and other users. Users are always talking with web applications through browsers.

  So, in order to test that our web application behaves correctly, we need a way to simulate this interaction between the browser and the web application in our tests. We need Mink.

Mike supports several ways to simulate a browser, through drivers.

Normal functional tests use BrowserTestBase, which uses the Goutte driver.

Javascript tests used to use the PhantomJS driver, but that is an abandoned project now.  This has been migrated to WebDriverTestBase, which uses the Selenium2 driver.

Selenium2 essentially does a remote control of a headless browser, through the WebDriver protocol.  This allows you to run the same driver against multiple browsers (Chrome, Firefox, and I think Safari).

The problem is that Selenium2 gives you the advantage of a real browser, but has limitations.  It is slow.  The other is that there isn't full parity between the other drivers, and getting the response code is one of these limitations.

So, this is a Mink/Selenium2 problem and not a genral Drupal testing framework problem.


How can I populate multiple blocks on a paginated page? my problem seemed simple to solve and how to do it.
But the paging did not work properly ..

As we see in the images, we have:

Main block with an image and description. It only shows 1 element.
Sequential block, an image and a description that the second content must show. It only shows 1 element. It is a block that is attached to the first
Third block with image and description showing the third content. It only shows 1 element. It is a block that is attached to the first
And at the end of a list of 3 cards, showing image and description. It must be shown from the third image onwards. It is a block that is attached to the first

It is content similar to news, the idea is to show different types of blocks for each content. And then paginate all the contents.
The problem I found is that when you attach elements or when doing so with blocks you can only page one block.
For example, when paging the main block, I will paginate all the attached blocks of an element. On the other hand, if I use the block of 3 cards, and I paginate it for this, I will paginate all the attached blocks with three elements.

The idea of mockups, would paginate the whole set with its corresponding content. That is, for the first page I have 6 elements shown in different ways, for the second page should show 6 to 12, the third 6 to 18. And to be more specific the main block will have the content 1 of page 1, the element 7 on page 2, and item 13 on page 3 and so on.

Example complete:

I hope you understand

I think building this functionality using custom code would be the way to go as views isn't really capable of this sort of thing.

If it was me I'd make a custom block to replicate this giving you alot more control.

But if you really want to use views you could maybe just have the 1 block and make it show 11 item per page. Then create a views template for the view and add some bits in there e.g. if you're using unformatted list you could copy views-view-unformatted.html.twig and save as views-view-unformatted--VIEWNAME--block-1.html.twig and then do something like:

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>

    {% if loop.index == 1 %}
     //use elements from $row to build display 1
    {% endif %}

    {% if loop.index == 2 %}
      //use elements from $row to build display 2
    {% endif %}
    ....
    ....
  </div>
{% endfor %}

Downsides of this you can't easily use different image styles or amount of text per row without using some contrib modules and other bits (I haven't actually attempted this but know there are modules to let you do more in twig, as mentioned custom block would be better though)


How can you alter the display of Flag confirmation dialog messages? One of the options for Flags is to have the flag automatically accept when the user clicks the link, or you can have it send the user to a confirmation dialog box where they have to click another button to confirm.

The default text for this dialog message is "Flag confirm", with a button to confirm and then a link for "Cancel".

"Flag confirm" is pretty obtuse, is there any way to alter the display of this dialog box? Thanks!

I figured this out.

When you create a new Flag, at the very bottom of the Flag set up screen is the option to choose if a dialog confirmation box is required for selecting your flag.

If you choose yes, an additional option box becomes available below this were you can set the message to be displayed when a user is either Flagging or Unflagging content with this dialog box.

If you don't enter any values (text string) in these fields, it seems the default text input by the system is "Flag confirm".


Can adding a cache tag create another cache row in database I want Node breadcrumbs to be updated when the content is updated, so I added the following code to my breadcrumb generation class:

// Set cache tags
$node_cache_tag = 'node:'.$node->id();
$breadcrumb->addCacheTags(array($node_cache_tag));

My concern is that this is a bad idea for sites with a lot of content (300,000+).  I saw this post https://www.drupal.org/node/2891281 and noted that the default cache row limit is 5,000. Would the above code be an issue with over 300,000 nodes? Should I cache the breadcrumbs based on the taxonomy term that created the breadcrumbs (~1300 terms)?

First of all you should add tags of all nodes/terms you use to build the breadcrumb. You can't set too many tags, because a tag doesn't influence how many cache entries are stored.

This is only a problem you have by adding cache contexts. By default this is url.path.parent. But if you use for example the title of the current node, then you need url.path. When you have 300.000 nodes this can indeed make caching quite useless and you could consider setting a cache max-age of 0 to disable caching. Perhaps by doing this you also benefit from lazy loading of the breadcrumb block by Big Pipe, if this is for logged-in users, I've never tried this. And for anonymous users pages are cached for each path anyway.


Views Load More: Showing X number of item initially I have a view which shows 6 items per page using Views Load More (Ajax). However what I would like to do is, on the very first page I would like to show 6 items and when clicked on Load More button it should show 3 items and so on. Is it possible?

Well you could use this workaround.

Have a view with the initial 3 (#1-3). Then add another view below it with an offset of 3, so it shows #4-6. Thus, it will load 3 rows at a time.

You could just show the views back to back on the page or you could use the Insert View module, and have it load the #1-3 view at the header of the 2nd view.


Form validate without submit action I'm developing a site that it will use Services for the CRUD operations and ANGULARJS for the comunication frontend <-> backend.

Now when I want to insert a new content of content type FOO I will don't use the standard form (node/add/FOO), but one of my HTML form, this because, like I said, I will use Services to store the new content.

So, is there a way (or a module) that permit me to send this form to Drupal for only validating it and give back a ok/error code? In this last case I need to receive back errors and the wrong fields.

Thanks. M.

What about this approach (these are just my thoughts)? So, create a rout which gets request and builds $form_state and calls drupal_form_submit function, actual form looks something like this:

function myForm($form, &$form_state)
{
  ....
  $form['submit'] = array(
    '#type' => 'submit',
    '#submit' => array(),
    '#validate' => array('myFormValidation')
  );
  ....
}

function myFormValidation($form, &$form_state)
{
  $error = false;
  if (SOME_CONDITION) {
    $error = true;
  }

  ...

  if (!$error) {
   drupal_json_output(array('ok'));
   exit;
  }
  else {
   drupal_json_output(array('error'));
   exit;
  }
}

EDIT:

I don't have an expirience with Drupal's Services module or its RESTFul services, but I usually develope my REST projects (usually backend system for IOS apps) in symfony, I think I understand how all this stuff work:), So when I wrote about a rout I meant that this will be some menu item (with hook_menu):

$items['check-my-external-post-data'] = array(
  'page callback' => 'some_callback',
  ...
);
...

function some_callback()
{
  ...
  // $values - from $_POST request
  $form_state = array();
  foreach ($values as $key => $value) {
    $form_state['values'][$key] = $value;
  }
  ...
  drupal_form_submit('myForm', $form_state);
}

I've never tested this kind of things, but it should work (there are too many tutorials about REST APIs, request handling, and so on.. which can help OP if something goes wrong)


Proxying a subdirectory to a remote site The goal

Make all requests to a previously static page at https://www.example.com/sub/folder on server 1 (Proxy) ACTUALLY go to a Drupal site at https://other.example.com on server 2 (Origin)

This is also getting setup as a multisite, because there are sub/folder2, sub/folder3, etc. that will need to be converted to Drupal sites. I don't think this has anything to do with the problem, but for the sake of completeness, I'm adding the sites.php changes too below.

What I've done so far

Changes on Server 1 (Proxy): Apache config

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} ^/sub/folder
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
SSLProxyEngine On
<Location /sub/folder>
  ProxyPass https://other.example.com/
  ProxyPassReverse https://other.example.com/
  ProxyPassReverseCookiePath / /sub/folder
</Location>

Changes on Server 2 (Origin): settings.php and sites.php

sites.php (because of multisite; and sites/sitename/settings.php is the file I'll be referencing below)

$sites['other.example.com'] = 'sitename';
$sites['www.example.com.sub.folder'] = 'sitename'; // I don't think this one is necessary, but just in case?

Aside from the standard DB setup in settings.php, the following has been added:

// $base_url allows for links/URIs to be generated properly
// Changing the REQUEST_URI seems to have fixed form issues, like the search block/form
// Not sure if the cookie_domain is doing anything/working properly
if (isset($_SERVER['HTTP_X_FORWARDED_HOST']) && $_SERVER['HTTP_X_FORWARDED_HOST'] == 'www.example.com') {
  $base_url = 'https://www.example.com/sub/folder'; // NO trailing slash!
  $_SERVER['REQUEST_URI'] = '/sub/folder' . $_SERVER['REQUEST_URI'];
  // (Edit) note don't put 'http' in front of this
  $cookie_domain = '.other.example.com';
}
...
$conf['reverse_proxy'] = TRUE;
...
$conf['reverse_proxy_addresses'] = array('ip.of.origin.server');

The problems

Trying to login through www.example.com/sub/folder/user validates (according to Drupal log)... but then it treats the page re-load as an anonymous user and fails access. Presumably, the cookie gets broke/lost/invalidated somehow in between. So, authenticated access to the server has to be done through other.example.com Not a huge problem (since the average Joe won't be logging in), but...
There's just a lot of annoying things occuring having to deal with fixing user/content created links and URIs. Currently, links that are first viewed after a cache clear are cached as whatever domain they're being viewed from. (This happened from using Pathologic module to force absolute URLs.) I realize this might not have been the BEST solution--using Pathologic--but if I fix problem 1., this should become a moot point.

So, I think I've got some kind of SSL/Proxy cookie issue at this point... any suggestions?

Drupal should be able to install into a sub-directory and "just work" without fiddling around with it. This question already answers this particular sub-directory issue:

How to get Drupal 7 installed in a sub-folder / sub-directory properly?

Try re-installing a fresh installation into the sub-directory. Can you login? The .htaccess of 2.site.com should have nothing to do with the issue at hand regarding 1.site.com.

The reason for your problem is likely something along the lines of a clean-url issue fighting against your configurations. A fresh install will be the easiest way to resolve this particular issue.

Regarding this line:

  and I'd like only that subdirectory to go to an arbitrarily named
  server with a drupal install at, say "https://2.site.com"

The domain merely points to a directory. The domain ISN'T an actual file location. As such, this particular line doesn't seem to make any sense. If the issue is not resolved by simply clearing out and reinstalling Drupal in the sub-directory at hand, please re-state your question by providing more information, describe where these sub-directories are in the system root relative to each other and then describe which directory each domain points to. Don't describe domains AS directories because they aren't directories - they're pointers.


How to pass variables to overridden Twig template located in module? I'd like to pass a variable to an overridden Twig template that is located in my custom module (not in a theme).

Following this answer and this answer, I wrote this code in mymodule.module:

function mymodule_preprocess_page(array &$variables) {
  $variables['hello'] = 'world';
}

function mymodule_theme_suggestions_node_add_list(array $variables) {
  $suggestions = [];
  $suggestions[] = 'node_add_list__' . 'custom';
  return $suggestions;
}

function mymodule_theme() {
  return [
    'node_add_list__custom' => [
      'base hook' => 'node_add_list',
    ],
  ];
}

Then, I have added in mymodule/templates/node-add-list--custom.html.twig:

myvar: {{ hello }}

However nothing appears after "myvar: " when I refresh the page. I mention that I cleared the cache.

Is there something specific to manage when we use hook_preprocess_page() with hook_theme_suggestions_HOOK()/hook_theme()?

You need to function MYMODULE_preprocess_node_add_list.

function MYMODULE_preprocess_node_add_list(array &$variables) {
  $variables['hello'] = 'world';
}

This preprocess hook is actually called HOOK_preprocess_HOOK. See the last HOOK in its name? You need to target the 'base hook' which is node_add_list. So preprocess that instead of the page.


Assign terms to image field items This is what I'm trying to achieve.

1) The website has a gallery page which is made from one node, so each time uploading new images to the gallery, you just edit this one node.

2) EVA is attached to the node page, so images are rendered via Views using EVA on that node page.

3) It all works great and everything. But it needs this feature that some of those images needs to be featured at the home page with a slideshow. So to achieve all that we can use Views and etc. But how do I filter out which images to show? All images cannot be shown.

4) So when uploading images to the image_field it would be nice if you could somehow select (I was thinking tick/untick boxes for each item in the image field) which ones to show in the homepage slideshow.

5) To be more exact, I was thinking maybe you could somehow assign some taxonomy vocab called 'Featured' which would have terms 'Yes' and 'No'. So you tick 'Yes' to all images you want to be shown in the slideshow and then just apply those filters via Views.

But I cannot figure out how to do that part where you assign terms to image field items without writing custom modules, not a PHP guru, sadly. Also any other alternatives are welcome.

UPDATE: I came up with a nasty workaround by using image field Alt or Title fields for filtering out via Views, it does the job, but from SEO point-of-view this is wrong. I put 'featured' value in Alt field for images I want to show up on the homepage slideshow, but that's wrong from SEO position, because Alt field should contain unique titles for each images for search engines to read it. Tagging them all as 'featured' is misleading.

So that's what I'm looking for, would be nice if you could add tick boxes next to Alt and Title fields. I tried image_field_caption module, it adds custom textarea field next to Alt and Title, but has no Views support, and again, you need to write 'feature' for each image instead of ticking it.

All this makes more sense now though.

Cheers

Use a field collection instead of the straight up image field. The field collection would have an image field and a term reference, plus maybe more things once you see its power.
The trade off is that your views will become a bit more cumbersome to build, but only slightly.


module_invoke to create user search block not working I've done the following to create two search blocks:

$content_search = module_invoke('search', 'block_view', 'content_search');
$user_search = module_invoke('search', 'block_view', 'user_search');

And I then call the blocks as needed like so:

<?php print render($content_search['content']); ?>
<?php print render($user_search['content']); ?>

They render correctly and the content search works just fine, but running something through the user search block just searches content. I noticed that regardless of which block I use, they both go to the URL http://example.com/search/node/[search parameters]

(This is Drupal 7 BTW)

The search block only works for the default search type. From search_box_form_submit():

$info = search_get_default_module_info();
if ($info) {
  $form_state['redirect'] = 'search/' . $info['path'] . '/' . trim($form_state['values'][$form_id]);
}
else {
  form_set_error(NULL, t('Search is currently disabled.'), 'error');
}

The third parameters you're passing ('content_search', 'user_search') are ignored. Presumably your default search type is content and that's why you're being redirected to the content search in both forms.

You can build the correct search form pretty easily though:

$content_form = drupal_get_form('search_form', NULL, '', 'node');
$user_form = drupal_get_form('search_form', NULL, '', 'user');


Getting a specific value from form api in theme-settings.php In my custom theme I am developing, I have a form API setting in theme-settings.php that lets a user choose one of two options with a select menu as such:

 $form['txtr_settings']['general_settings']['choose_slideshow'] = array(
        '#type' => 'select',
        '#title' => t('Choose a slideshow'),
        '#default_value' => theme_get_setting('choose_slideshow'),
        '#options' => array(
            'basic' => t('Basic'),
            'fancy' => t('Fancy'),
        ),
    );

Then in my theme's page.tpl.php I want the value the user has selected to be part of an if else statement.

Right now I have this code which does not seem to work:

<?php if (theme_get_setting('choose_slideshow') == 'basic')
            include(dirname(__FILE__) . "/slideshow_alpha.inc");
        else
            include(dirname(__FILE__) . "/slideshow_beta.inc");
  ?>

I know if I have a simple single checkbox (checked = yes or '1' I can do something like this:

<?php if (theme_get_setting('choose_slideshow') == 1)

... but in this case I really want to show the user both options and have them choose one or the other in the select menu.

If I use either option on it's own without the if / else, each works fine so I think it's a question of my theme_get_setting value. I am not really sure if this is a Drupal question or a PHP question that I should ask over on Stack Exchange.

The way to really do this was to create variables in template.php using a preprocess function and take some of the logic out of page.tpl.php and to instead use the actual variables created. Based on this, my updated code that's working is:

template.php

function my_theme_preprocess_page(&$variables) {
 // create variables for each slideshow
  $variables['slideshow_alpha'] = (theme_get_setting('choose_slideshow') == 'alpha');
  $variables['slideshow_beta'] = (theme_get_setting('choose_slideshow') == 'beta');
}

... and then in page.tpl.php

 <?php if ($slideshow_alpha): ?>
    <?php require_once dirname(__FILE__) . '/slideshow_alpha.inc'; ?>
  <?php else: ?>
    <?php require_once dirname(__FILE__) . '/slideshow_beta.inc'; ?>
  <?php endif; ?>

It's important to note that what helped me figure much of the code updates out were running it through PAReview.sh. However, I did not want to set up the module and there is an online version which works great but your code needs to be in a git repo on drupal.org so you would have to set up a simple sandbox project to test your code. The online version is on ventral.org and it's what drupal.org uses to review projects. The new updated code also does not throw any errors with the code sniffer an the old code did.


How can I restrict external URLs in link field to allow only certain domains? After creating a Link field and use the Link with service icon format, I find out that there is no option to restrict external URLs to external domains that I want
For example, if I only want to allow Twitter links, something like add https://www.twitter.com/*.
Someone already asked here, but it seems that the Advanced Link module is not available for my Drupal version.
With what module and how can I filter my desired URLs in Drupal 9?

You need to write your own custom validation contraint and add this constraint to your field.
Docs: https://www.drupal.org/docs/drupal-apis/entity-api/entity-validation-api/providing-a-custom-validation-constraint
I've used that example to create a "force HTTPS" link field constraint
src/Plugin/Validation/Constraint/Https.php
<?php

namespace Drupal\MYMODULE\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Checks that the submitted URL is starting with https://
 *
 * @Constraint(
 *   id = "MY_CONSTRAINT_ID",
 *   label = @Translation("Https", context = "Validation"),
 *   type = "string"
 * )
 */
class Https extends Constraint {
  public $notHttps = '%uri is not a secure site (not starting with https://)';
}

src/Plugin/Validation/Constraint/HttpsValidator.php
<?php

namespace Drupal\MYMODULE\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the Https constraint.
 */
class HttpsValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {
    $item = $items->first();
    if (!isset($item)) {
      return NULL;
    }

    foreach ($items as $item) {
      /* CHANGE THIS, e.g. here you can check for domain names */
      if (strpos($item->uri, 'https://') !== 0) {
        $this->context->addViolation($constraint->notHttps, ['%uri' => $item->uri]);
      }
    }
  }
}

MYMODULE.module
<?php

use Drupal\Core\Entity\EntityTypeInterface;

function MYMODULE_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  if ($bundle === 'MY_ENTITY_BUNDLE' && $entity_type->id() == 'MY_ENTITY_TYPE') {
    if (isset($fields['MY_FIELD'])) {
      $fields['MY_FIELD']->addConstraint('MY_CONSTRAINT_ID', []);
    }
  }
}


Duplicates when creating view with entity reference I have a content type called Conference and there are various sections of data attached to each conference such as guest speakers, agenda, and local amenities. These sections of data are entity bundles. These attach to the content type with an entity reference field on the bundle, so each bundle has a list of conferences in a select list and you attach the bundle to conference by selecting it in this list.

The problem has come when creating a view to display the conference content type with it's corresponding entity bundle information, I am getting a views-row for every bundle, so the basic information from the content type is being duplicated 8-9 times and the bundle data is showing once, and each bundle shows on a views-row where all other bundle info is missing apart from its own.

I have tried to turn on DISTINCT in query settings but not working and if I turn on aggregation I get this error

SQLSTATE[42000]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near the keyword 'AS'.

My View uses a contextual filter for nid and an entity reference relationship to pull the values through.

Any help is welcome, thanks as I am completely stuck with this. Maybe there is a work around, or maybe I need to set up my views differently?

You can give a try to Views Distinct module.

Also, if there the results the logically different you can think of showing them in way that they look more of information rather than repeated results
For example if you group by conference, you can show aggregated speakers for a given conferenece


How can I change form action link? How can I change form action in drupal 8?

In default, page not change and when my form path is /site/drupal/page, my form action is <form data-drupal-selector="test" action="/site/drupal/page" method="post" id="test" accept-charset="UTF-8">.

But I want change it to other page. How can I do this ?

** Redirect not worked, see this link: Redirect after submit form

In the form submit handler, you can modify the $form['action'] value.

// Get the routename
$routename = 'My-Route';
  $url = \Drupal\Core\Url::fromRoute($routename);
  // make the redirection
  $form['#action'] = $url->toString();


Programmatically create an entity I created an entity via Entity Construction Kit, Initially I wanted to use rules to create the new entity but the entity is fielded and the fields don't get exposed in rules (as of now, someone is trying to work on a patch for that), but in the interm I wanted to write a simple function that creates a entity, which I assumed would be somewhat like creating a node programmatically, but I've been at this for like 4 hours and I haven't gained an inch, I have entity_create and entity_save but they don't do much and I can't find any documentation on it.

What I'd like to see is how to create an example entity from a bundle made with eck, or through code, that is fielded.

Thanks so much

Edit: The last thing I need to figure out is how to specify the name of the fields that are attached to the entity so I can enter values for those as well.

$values = array('uid' => 1, 'field_receipt_prod_ref' => 1, 'type' => 'receipt');
$new_ent = entity_create('receipt', $values)->save();

The simpler approach is with the help of entity_metadata_wrapper().

$e = entity_create($entityType, array('type' => $bundleName));
$ew = entity_metadata_wrapper($entityType, $e);
$ew->field_name->set('value');
$ew->save();


How can I switch to an external db with Views API? In Drupal 7 I have a module with a hook_form(). This form is saving data into an external postgresql database.

I want to create a views to display data recorded. So I used hook_views_data() to create a mapping between the view and my custom tables. I created a view with admin but in this view I have the following error :

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cars' doesn't exist

I have tried something like this but it doesn't run :

function carshop_views_pre_render(&$view) {
  if ($view->name == 'cars_overview') {
    db_set_active('carsdb');
  }
db_set_active();
}

Sounds as if you need the Views Database Connector module.

From the project page:

  Views Database Connector is a powerful module that gives Views full access to external database tables found in the settings for your Drupal installation. With this module, you can setup a view around any table in any database configuration. This can be extremely useful to pull external data from a database to show to your users in a view.


Is it possible to hide the title of a block in a region to render it separately from the content? I'm styling a custom region for the "Active Forum Topics Block" that's included with Drupal. can I hide certain elements in region--[name].tpl.php like as it is done in node.tpl.php?

This is part of my node.tpl.php:

    // We hide the elements now so that we can render them later.
    hide($content['comments']);
    hide($content['links']);
    hide($content['field_image']);
    hide($content['links']['#links']['node-readmore']);
    hide($content['links']['#links']['comment-add']);
    hide($content['field_tags']);

I would like to do this if it's possible in region--forum_topics.tpl.php (example name "forum_topics"):

    hide($content['???']);

I don't know what the proper way is, for region.tpl.php. If this is possible, what can I put between brackets to hide the title of the block? If there is a documentation page I can see for more than just the block title, can you please link it?

It might be easier to do this in the block.tpl.php file (using $block->region to determine the region) as you have the title printed out separately from content there.

In your test environment you can also use stuff like these to get a better overview of complex variables (will help you with issues like this):

drupal_set_message('
'.var_export($content, TRUE).'
');

function print_r_html ($data) {
  ?>
<?php print_r($data); ?>
<?php
}