0

We have a content type named "Person", which has fields as Full Name, Age, Address etc.

There are thousands of people entries on the site. We are using Views to sort out people's list on different pages as per need.

Lately, there has been a requirement that we need to sort the list of people by Last Name. But the problem is that there's no last name field as there's only "Full Name" field of the person in the site.

I am using views to sort the results in the pages and I am not sure how to sort the results by last name. Is there any way I can achieve this?

May be I can create a field as "Last Name" in the content field but is there a way I can dynamically fill in the Last Name by extracting Last word from Full Name?

May be through someway in SQL?

Any idea or assistance would be highly appreciated.

Thanks.

  • 1
    Try this ALTER TABLE tbl_name` ADD LastName AS RIGHT(FullName, CHARINDEX(' ', REVERSE(FullName)) - 1) PERSISTED` – DRUPWAY Dec 2 '14 at 6:15
2

Here is my way of doing it:

  • Create a Computed Field to manipulate the substring (Last Name) and store it as a field

Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code.

The Computed Field module only updates its computed values on saves or on load (if no computed value is computed yet). This is not optimal when using computed values in lists etc., or if you should wish to change the logic in the computed field.

  • Use this Computed Field as a sort criteria in Views.
1

You can create a user defined function for this

With that function, you would be able to build your query as follows:

SELECT SPLIT_STR(fullname, ' ', 1) as fullfirst,
       SPLIT_STR(fullname, ' ', 2) as fulllast
FROM   users;

You can also do the following:

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 1), ' ', -1) as fullfirst,
       SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 2), ' ', -1) as fulllast
FROM   users;
  • Most welcome @user219492 – Nishant Dec 2 '14 at 9:00

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.