Answers.Body: <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>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-28T16:57:15.270Z
Answers.Text: That is what I was looking for, thank you.  Why would you not recommend it?  Why are they better in php?
Answers.UserDisplayName: Alex Carpenter
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-28T17:14:52.460Z
Answers.Text: 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
Answers.UserDisplayName: Robin Schambach
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-28T18:05:12.757Z
Answers.Text: 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.
Answers.UserDisplayName: Alex Carpenter
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-28T18:13:48.690Z
Answers.Text: 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.
Answers.UserDisplayName: Robin Schambach
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-28T18:19:36.003Z
Answers.Text: That is good to know, thank you.  I will look more into implementing php in craft.
Answers.UserDisplayName: Alex Carpenter
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-28T19:37:51.690Z
Answers.Text: Do you know of any tutorial series that cover including php in Craft projects?
Answers.UserDisplayName: Alex Carpenter
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-28T19:40:08.090Z
Answers.Text: 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
Answers.UserDisplayName: Robin Schambach
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-28T20:34:52.170Z
Answers.Text: 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
Answers.UserDisplayName: Alex Carpenter
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-28T20:38:19.103Z
Answers.Text: You need to pass an element to the function, seems like you pass null
Answers.UserDisplayName: Robin Schambach
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-28T20:47:55.577Z
Answers.Text: 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.
Answers.UserDisplayName: Alex Carpenter
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-28T20:54:49.463Z
Answers.Text: 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
Answers.UserDisplayName: Robin Schambach
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-28T21:30:17.870Z
Answers.Text: 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.
Answers.UserDisplayName: Alex Carpenter
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-29T18:06:17.633Z
Answers.Text: 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.
Answers.UserDisplayName: Alex Carpenter
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-29T19:15:27.363Z
Answers.Text: What is a `matrix entry`? entries and matrix blocks are both elements, they work exactly the same in that manner
Answers.UserDisplayName: Robin Schambach
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-29T20:01:32.180Z
Answers.Text: 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.
Answers.UserDisplayName: Alex Carpenter
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-29T20:06:14.537Z
Answers.Text: 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"
Answers.UserDisplayName: Robin Schambach
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-29T20:19:23.230Z
Answers.Text: 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.
Answers.UserDisplayName: Alex Carpenter
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-28T16:21:34.763Z
Answers.LastActivityDate: 2018-08-28T16:21:34.763Z
Answers.UserDisplayName: Robin Schambach
Answers.Body: <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>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-28T01:03:55.197Z
Answers.Text: 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.
Answers.UserDisplayName: Alex Carpenter
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-08-27T23:44:04.947Z
Answers.LastActivityDate: 2018-08-27T23:44:04.947Z
Answers.UserDisplayName: Dalton Rooney
Body: <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>
  
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2018-08-28T08:58:09.037Z
Comments.Text: 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
Comments.UserDisplayName: Robin Schambach
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2018-08-28T15:13:53.267Z
Comments.Text: I am storing everything in users. What is the way?
Comments.UserDisplayName: Alex Carpenter
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2018-08-28T16:22:24.853Z
Comments.Text: There is no "best" way. Each approach has advantages and disadvantages, you need to choose the solution that fits your needs
Comments.UserDisplayName: Robin Schambach
Tags: <craft3>
Title: How to update a field when a user views a page
ThreadText: # 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
  
  ```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.  
  
  ---
  
  