0

I have a link field for a content type. I am implementing a validation where users cannot enter a domain name in the field if it has been used already. For that purpose, I need a direct way to derive domain from the field value (full url) for comparison with the domain name of the url entered.

$result = \Drupal::entityQuery('node')
->condition('type', 'ABC')
->condition('field_1', parse_url($url_entered)['host']->execute();

The problem is field_1 is a full url where as I only want validation over the domain name.

Is it possible to do using Entity Query? If not, any suggestions?

0

To do so you can use LIKE operator in your query like the following:

$host = parse_url($url_entered)['host'];
$result = \Drupal::entityQuery('node')
  ->condition('type', 'ABC')
  ->condition('field_link', "%" . $host . "%", 'LIKE')->execute();

UPDATE
if you want to check that the exact host exist, you should select all values of your field and then compare with the entered host.

$host = parse_url($url_entered)['host'];
// Select all uris of field link.
$database = \Drupal::database();
$query = $database->select('node__field_link', 'nfl')
  ->condition('nfl.bundle', 'page')
  ->fields('nfl', ['field_link_uri']);
$result = $query->execute()->fetchAll(PDO::FETCH_COLUMN, 0);
$hosts = [];
// extract all hosts.
foreach ($result as $item){
  $hosts[] = parse_url($item)['host'];
}
// Check if the host already exist.
if (in_array($host, $hosts)){
  // Do what you want ici !
}
4
  • This does not work because we would end up blocking domains like 'Axyz.com', if 'xyz.com' has been entered. The solution I am looking for is a way to get the host from the field_link and then do the comparison. – aroopk Dec 8 '20 at 5:01
  • check my update ! – berramou Dec 8 '20 at 10:29
  • Thank you! This works. – aroopk Dec 9 '20 at 11:31
  • You are so welcome, glad that helped, marked as the accepted answer if someone else needs it in the future – berramou Dec 9 '20 at 12:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.