<p>You can do a quick and dirty work around and just store the element in each request via Twig</p>

<pre class="lang-twig prettyprint-override"><code>{% set lastVisitor = user.lastvisitor.one() %}
{% if currentUser != null and currentUser.id != lastVisitor.id %}
    {# new user -&gt; set the field value of user -&gt; relate the currentUser #}
    {% do user.setFieldValue('lastVisitor', [currentUser.id]) %}
    {# save the element #}
    {% do craft.app.getElements().saveElement(user) %}
    {% if user.hasErrors %}
        {# print errors via user.getErrors() %}
    {% endif %}
{% endif %}
</code></pre>

<p>I would not recommend it even if it is possible. Those things are better in PHP than in Twig</p>

CC BY-SA 4.0
2018-08-28T16:57:15.270Z
That is what I was looking for, thank you.  Why would you not recommend it?  Why are they better in php?
Alex Carpenter
CC BY-SA 4.0
2018-08-28T17:14:52.460Z
Because Twig is not supposed to contain too much business logic. The idea to use an MVC pattern is to separate your logic and your templates. With that in mind It's not really clean to mix them together. Error handling and debugging is easier in PHP as well. Imagine someone looks at this project in about 3 years. Experienced developers / experienced Craft developers will always search for the logic in services or links to those functions in variables or controllers, not in templates
Robin Schambach
CC BY-SA 4.0
2018-08-28T18:05:12.757Z
Ah good point.  I didn't realize Craft was set up to deal with things that way.  I thought php was only used for plugins.  The few tutorials I have done have done everything in twig which made seem like it was better to keep everything possible in twig and only result to php for plugins for more complicated tasks.
Alex Carpenter
CC BY-SA 4.0
2018-08-28T18:13:48.690Z
No most tutorials are about Twig because the minority of people is willing/able to use PHP but that doesn't mean it's the best way.
Robin Schambach
CC BY-SA 4.0
2018-08-28T18:19:36.003Z
That is good to know, thank you.  I will look more into implementing php in craft.
Alex Carpenter
CC BY-SA 4.0
2018-08-28T19:37:51.690Z
Do you know of any tutorial series that cover including php in Craft projects?
Alex Carpenter
CC BY-SA 4.0
2018-08-28T19:40:08.090Z
As far as I know, there are none for Craft 3 yet. Your only resource is the source code, craft 3 docs, yii2 docs SE, Slack and a few pages that are about Craft but those only handle a few specific scenarios. I always suggest to read the source code and ask at Slack /SE
Robin Schambach
CC BY-SA 4.0
2018-08-28T20:34:52.170Z
That adds quite an obstacle for someone just starting.  I can't get this to not give this error either: Argument 1 passed to craft\services\Elements::saveElement() must implement interface craft\base\ElementInterface, null give
Alex Carpenter
CC BY-SA 4.0
2018-08-28T20:38:19.103Z
You need to pass an element to the function, seems like you pass null
Robin Schambach
CC BY-SA 4.0
2018-08-28T20:47:55.577Z
I understood that but not how to fix it, everything I try based on this code gives me null.{% do user.setFieldValue('lastVisitor', [currentUser.id]) %}
{% do craft.app.getElements().saveElement(user) %} is always null, even when I try different variations of the first do statement.
Alex Carpenter
CC BY-SA 4.0
2018-08-28T20:54:49.463Z
What do you mean by "gives you null"? The `setFieldValue` doesn't return something, it's not supposed to return something other than `null`. Make sure your user is an element. I just worked with the example code you gave us
Robin Schambach
CC BY-SA 4.0
2018-08-28T21:30:17.870Z
I am very confused lol.  `{% set applicant = craft.users()
    .id(id)
    .one() %}
{% set visitor = applicant.comments[0] %} 
    {% do visitor.setFieldValue('lastvisitor', [currentUser.id]) %}
{% do craft.app.getElements().saveElement(visitor) %}` Doesn't give an error but also doesn't actually save the value into lastvisitor in the craft users panel.  I seem to be lacking the fundamental understanding of either what is happening or the syntax involved.
Alex Carpenter
CC BY-SA 4.0
2018-08-29T18:06:17.633Z
I figured out what the problem is.  It works for a regular entry, but I was trying to get it to work for a matrix entry.
Alex Carpenter
CC BY-SA 4.0
2018-08-29T19:15:27.363Z
What is a `matrix entry`? entries and matrix blocks are both elements, they work exactly the same in that manner
Robin Schambach
CC BY-SA 4.0
2018-08-29T20:01:32.180Z
Well a matrix block.  It works for standard entries but not for a matrix block. I played with the syntax and sometimes it does nothing and sometimes it erases all previous entries without adding a new one.
Alex Carpenter
CC BY-SA 4.0
2018-08-29T20:06:14.537Z
You should have mentioned it should **add** a new one from the beginning. That's an entirely new question, I thought asked about updating one, because your headline was "How to update a field when a user views a page"
Robin Schambach
CC BY-SA 4.0
2018-08-29T20:19:23.230Z
I meant it isn't doing either.  It will either do nothing or erase all blocks leaving nothing in its place. Nothing if the fieldValue is lastvisitor (a block on comments) or erase everything if it is comments (the matrix block handle) Either way this seems to have gone on a tangent, I created a new one that is hopefully simpler.  [https://craftcms.stackexchange.com/questions/27513/save-matrix-in-twig-syntax] For this I was just mentioning where the confusion was and I got it to work on normal entries.  Thank you for the help.
Alex Carpenter
CC BY-SA 4.0
2018-08-28T16:21:34.763Z
2018-08-28T16:21:34.763Z
Robin Schambach
<p>There's a plugin called <a href="https://github.com/putyourlightson/craft-entry-count" rel="nofollow noreferrer">Entry Count</a> that updates a counter record every time a visitor loads a page. You might be able to adapt that plugin to check to see if the user is logged in, and if so, record their user ID to the database instead of incrementing the hit counter. The value is displayed on the Craft entry list dashboard, you would just want to adapt that to display the username instead of the ID.</p>

CC BY-SA 4.0
2018-08-28T01:03:55.197Z
Is there no simple way to save data without a form in twig?  A plugin would require a lot of modifications because it isn't related to specific pages, it is related to users that are dynamically generated.  I looked through the plugin and it seems simple enough, but nowhere near as succinct as saving an entry like with a form.  I can do it with javascript but I was hoping there was something craft specific I wasn't aware of yet.
Alex Carpenter
CC BY-SA 4.0
2018-08-27T23:44:04.947Z
2018-08-27T23:44:04.947Z
Dalton Rooney
<p>I am building a site for a client that is effectively a job board with a messaging system.  They want to know who the last person in their office was to view a specific application and to know who/when someone views specific pages/messages.  </p>

<p>I am hoping for something like </p>

<pre><code>set x = users.lastvisitor 
if currentuser != users.last vistor
insert currentuser &amp; date into users.lastvisitor 
</code></pre>

<p>Can anyone point me in a direction?  I am new to Craft so don't know how it handles things like this. I am using matrix blocks for the messages, is it possible to add an entry through a query instead of a form?</p>

CC BY-SA 4.0
2018-08-28T08:58:09.037Z
Which field layout contains the field? Is the field in your user or in the entry? There is actually a really simple way to achieve this
Robin Schambach
CC BY-SA 4.0
2018-08-28T15:13:53.267Z
I am storing everything in users. What is the way?
Alex Carpenter
CC BY-SA 4.0
2018-08-28T16:22:24.853Z
There is no "best" way. Each approach has advantages and disadvantages, you need to choose the solution that fits your needs
Robin Schambach
<craft3>
How to update a field when a user views a page
# How to update a field when a user views a page

(Asked by: username_0 on 2018-08-27)

I am building a site for a client that is effectively a job board with a messaging system.  They want to know who the last person in their office was to view a specific application and to know who/when someone views specific pages/messages.  
I am hoping for something like 
set x = users.lastvisitor 
if currentuser != users.last vistor
insert currentuser & date into users.lastvisitor 

Can anyone point me in a direction?  I am new to Craft so don't know how it handles things like this. I am using matrix blocks for the messages, is it possible to add an entry through a query instead of a form?

**Tags:** craft3

> **Comments:**
> **username_1**: Which field layout contains the field? Is the field in your user or in the entry? There is actually a really simple way to achieve this  
> **username_0**: I am storing everything in users. What is the way?  
> **username_1**: There is no "best" way. Each approach has advantages and disadvantages, you need to choose the solution that fits your needs  

---

## 2 answers

### Answer by username_1 on 2018-08-28. Score: 1 | Accepted answer

You can do a quick and dirty work around and just store the element in each request via Twig
{% set lastVisitor = user.lastvisitor.one() %}
{% if currentUser != null and currentUser.id != lastVisitor.id %}
    {# new user -> set the field value of user -> relate the currentUser #}
    {% do user.setFieldValue('lastVisitor', [currentUser.id]) %}
    {# save the element #}
    {% do craft.app.getElements().saveElement(user) %}
    {% if user.hasErrors %}
        {# print errors via user.getErrors() %}
    {% endif %}
{% endif %}

I would not recommend it even if it is possible. Those things are better in PHP than in Twig

> **Comments:**
> **username_0**: That is what I was looking for, thank you.  Why would you not recommend it?  Why are they better in php?  
> **username_1**: Because Twig is not supposed to contain too much business logic. The idea to use an MVC pattern is to separate your logic and your templates. With that in mind It's not really clean to mix them together. Error handling and debugging is easier in PHP as well. Imagine someone looks at this project in about 3 years. Experienced developers / experienced Craft developers will always search for the logic in services or links to those functions in variables or controllers, not in templates  
> **username_0**: Ah good point.  I didn't realize Craft was set up to deal with things that way.  I thought php was only used for plugins.  The few tutorials I have done have done everything in twig which made seem like it was better to keep everything possible in twig and only result to php for plugins for more complicated tasks.  
> **username_1**: No most tutorials are about Twig because the minority of people is willing/able to use PHP but that doesn't mean it's the best way.  
> **username_0**: That is good to know, thank you.  I will look more into implementing php in craft.  
> **username_0**: Do you know of any tutorial series that cover including php in Craft projects?  
> **username_1**: As far as I know, there are none for Craft 3 yet. Your only resource is the source code, craft 3 docs, yii2 docs SE, Slack and a few pages that are about Craft but those only handle a few specific scenarios. I always suggest to read the source code and ask at Slack /SE  
> **username_0**: That adds quite an obstacle for someone just starting.  I can't get this to not give this error either: Argument 1 passed to craft\services\Elements::saveElement() must implement interface craft\base\ElementInterface, null give  
> **username_1**: You need to pass an element to the function, seems like you pass null  
> **username_0**: I understood that but not how to fix it, everything I try based on this code gives me null.{% do user.setFieldValue('lastVisitor', [currentUser.id]) %} {% do craft.app.getElements().saveElement(user) %} is always null, even when I try different variations of the first do statement.  
> **username_1**: What do you mean by "gives you null"? The `setFieldValue` doesn't return something, it's not supposed to return something other than `null`. Make sure your user is an element. I just worked with the example code you gave us  
> **username_0**: I am very confused lol.  `{% set applicant = craft.users()     .id(id)     .one() %} {% set visitor = applicant.comments[0] %}      {% do visitor.setFieldValue('lastvisitor', [currentUser.id]) %} {% do craft.app.getElements().saveElement(visitor) %}` Doesn't give an error but also doesn't actually save the value into lastvisitor in the craft users panel.  I seem to be lacking the fundamental understanding of either what is happening or the syntax involved.  
> **username_0**: I figured out what the problem is.  It works for a regular entry, but I was trying to get it to work for a matrix entry.  
> **username_1**: What is a `matrix entry`? entries and matrix blocks are both elements, they work exactly the same in that manner  
> **username_0**: Well a matrix block.  It works for standard entries but not for a matrix block. I played with the syntax and sometimes it does nothing and sometimes it erases all previous entries without adding a new one.  
> **username_1**: You should have mentioned it should **add** a new one from the beginning. That's an entirely new question, I thought asked about updating one, because your headline was "How to update a field when a user views a page"  
> **username_0**: I meant it isn't doing either.  It will either do nothing or erase all blocks leaving nothing in its place. Nothing if the fieldValue is lastvisitor (a block on comments) or erase everything if it is comments (the matrix block handle) Either way this seems to have gone on a tangent, I created a new one that is hopefully simpler.  [https://craftcms.stackexchange.com/questions/27513/save-matrix-in-twig-syntax] For this I was just mentioning where the confusion was and I got it to work on normal entries.  Thank you for the help.  

---

### Answer by username_2 on 2018-08-27. Score: 1

There's a plugin called [Entry Count](https://github.com/putyourlightson/craft-entry-count) that updates a counter record every time a visitor loads a page. You might be able to adapt that plugin to check to see if the user is logged in, and if so, record their user ID to the database instead of incrementing the hit counter. The value is displayed on the Craft entry list dashboard, you would just want to adapt that to display the username instead of the ID.

> **Comments:**
> **username_0**: Is there no simple way to save data without a form in twig?  A plugin would require a lot of modifications because it isn't related to specific pages, it is related to users that are dynamically generated.  I looked through the plugin and it seems simple enough, but nowhere near as succinct as saving an entry like with a form.  I can do it with javascript but I was hoping there was something craft specific I wasn't aware of yet.  

---

