Answers.Body: <p>If your <code>imageFamily</code> field is an image field, you can't assign the POST value directly to the field. You need to first save the image as an asset, then assign the ID of the asset to the <code>imageFamily</code> field.</p>
  <p>Saving an uploaded image as a new asset requires a bit of boilerplate code. You can use the <a href="https://github.com/craftcms/cms/blob/3fe8e67e1026084c282ced906617a78f175174f2/src/controllers/AssetsController.php#L227-L364" rel="nofollow noreferrer"><code>AssetsController::actionUpload</code> endpoint</a> as a starting point. You need something like this (quick and untested, might need some adjustments):</p>
  <pre class="lang-php prettyprint-override"><code>use Craft;
  use craft\elements\Asset;
  use craft\helpers\Assets;
  use craft\web\UploadedFile;
  
  $uploadedFile = UploadedFile::getInstanceByName('img');
  $tempPath = $uploadedFile-&gt;saveAsTempFile();
  
  $volume = Craft::$app-&gt;getVolumes()-&gt;getVolumeByHandle('uploads');
  $folder = Craft::$app-&gt;getAssets()-&gt;ensureFolderByFullPathAndVolume('family-photos', $volume, false);
  
  $asset = new Asset();
  $asset-&gt;newFolderId = $folder-&gt;id;
  $asset-&gt;volumeId = $volume-&gt;id;
  $asset-&gt;tempFilePath = $tempPath;
  $asset-&gt;setFilename(Assets::prepareAssetName($uploadedFile-&gt;name)); 
  $asset-&gt;avoidFilenameConflicts = true;
  $asset-&gt;setScenario(Asset::SCENARIO_CREATE);
  
  Craft::$app-&gt;elements-&gt;saveElement($asset)
  </code></pre>
  <p>Then once the asset was saved, you can assign it to your entry. A tiny gotcha is that the assets field expects an <em>array</em> of asset IDs and won't accept a single asset ID:</p>
  <pre class="lang-php prettyprint-override"><code>$family-&gt;setFieldValue('myCustomField', [$asset-&gt;id]);
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-10T14:10:23.473Z
Answers.Text: Ah , that is , the scenario is like this. First you need to upload an image, and then find it and assign it to the created record. It's clear. But where should I place the code you proposed? Sorry for the stupid question, I'm a beginner
Answers.UserDisplayName: Dimi
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-10T14:13:09.910Z
Answers.Text: All I have now is one FamiliesController, which I described in my question and the form. Moreover, it works, but does not add images.
Answers.UserDisplayName: Dimi
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-10T14:22:24.127Z
Answers.Text: or it can simply be supplemented directly in the  controller file FamiliesController?
Answers.UserDisplayName: Dimi
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-10T14:22:29.407Z
Answers.Text: @Dimi You can do everything in one Controller action. Create the asset using the code above and validate that the asset was saved successfully (check the return value of `Craft::$app->elements->saveElement`, it will return `false` if an error occured). If everything is fine, proceed to create an entry and assign the new asset to the assets field.
Answers.UserDisplayName: MoritzLost
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-10T14:24:35.150Z
Answers.Text: Thank you so much for your help... I'll try to do it later. I will write a little later whether I succeeded or not
Answers.UserDisplayName: Dimi
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-17T22:26:10.663Z
Answers.Text: I tried to take your code and put it in my controller. I have deleted everything unnecessary. At the moment, the controller should only upload files to the "uploads" directory. But unfortunately the code gives an error: Unknown Property – yii\base\UnknownPropertyException Getting unknown property: modules\families\controllers\FamiliesController::volumes I thought it was because of the uploads directory. I checked it! The directory exists! What could be the reason?
Answers.UserDisplayName: Dimi
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-17T22:28:33.640Z
Answers.Text: The error is currently in this line: $volume = $this->volumes->get volume by descriptor("downloads");
Answers.UserDisplayName: Dimi
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-18T07:35:23.063Z
Answers.Text: @Dimi Ah, that was a leftover from my codebase. You need to use the `\Craft::$app` singleton to get the volumes and assets services. Updated in the code example above!
Answers.UserDisplayName: MoritzLost
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-18T13:52:25.217Z
Answers.Text: Indeed! I have made corrections, there is no more error, but another one has appeared. I suspect it is related to the file name. Error: Invalid Configuration – yii\base\InvalidConfigException
  Asset not configured with its filename
Answers.UserDisplayName: Dimi
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-18T14:01:13.237Z
Answers.Text: @Dimi Guess you need to explicitly set the filename. Updated the example code. Please note that it's only a starting point, you may need to customize this further and/or set additional properties.
Answers.UserDisplayName: MoritzLost
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-18T14:13:37.427Z
Answers.Text: That's right, these are just the basic settings that allow you to upload a file. I made the latest corrections, the code is working. I think when creating this form, it is necessary to take into account the uniqueness of this file, the maximum weight of the image. What is the best way to check the weight of a file?
Answers.UserDisplayName: Dimi
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-18T20:15:29.257Z
Answers.Text: You mean the file size? You can check the filesize on the original posted file or on the `UploadedFile` instance. But please create a new question for this, since it has not much to do with the original question. If your original problem is solved, don't forget to mark an answer as accepted.
Answers.UserDisplayName: MoritzLost
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-19T09:28:15.030Z
Answers.Text: Yes, you have been very helpful in this matter, thank you. I put your answer as a solution. Regarding the weight of the file, I have created a separate question: https://craftcms.stackexchange.com/questions/41801/how-can-i-check-the-size-of-the-file-uploaded-via-the-form
Answers.UserDisplayName: Dimi
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-10T13:54:12.407Z
Answers.LastActivityDate: 2024-06-18T14:00:20.017Z
Answers.LastEditDate: 2024-06-18T14:00:20.017Z
Answers.UserDisplayName: MoritzLost
Answers.Body: <p>You should be using the <a href="https://docs.craftcms.com/api/v4/craft-base-elementinterface.html#method-setfieldvalue" rel="nofollow noreferrer"><code>setFieldValue()</code></a> method to set the value of a custom field, as documented at <a href="https://craftcms.com/docs/4.x/extend/element-types.html#saving-custom-field-values" rel="nofollow noreferrer">https://craftcms.com/docs/4.x/extend/element-types.html#saving-custom-field-values</a></p>
  <pre class="lang-php prettyprint-override"><code>$family-&gt;setFieldValue('myCustomField', $img);
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-10T13:19:42.843Z
Answers.Text: I replaced it, but the result remains the same. I get the same error: Unknown Property – yii\base\UnknownPropertyException
  Setting unknown property: craft\behaviors\CustomFieldBehavior::imageFamilly
Answers.UserDisplayName: Dimi
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-10T13:24:54.537Z
Answers.Text: Although not. I had a typo. It was possible to send, but the picture was not added to the system. The imageFamily field in the system is empty
Answers.UserDisplayName: Dimi
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-10T13:25:13.687Z
Answers.Text: $family->setFieldValue('imageFamily', $img);
Answers.UserDisplayName: Dimi
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-10T13:47:50.790Z
Answers.Text: I came across an incomplete answer on the Internet that needs to be connected in my controller `use craft\web\UploadedFile;`  But I don't quite understand how to use it
Answers.UserDisplayName: Dimi
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-06-10T07:38:56.470Z
Answers.LastActivityDate: 2024-06-10T07:38:56.470Z
Answers.UserDisplayName: Ben Croker
Body: <p>please tell me how to add an entry that contains an image to the desired section. I use Craft CMS 4.9.6. At the moment, I have a form on my website:</p>
  <pre><code>&lt;form method=&quot;POST&quot;&gt;
      {{ csrfInput() }}
      {{ actionInput('families/families/start') }}
      &lt;input type=&quot;text&quot; name=&quot;name&quot; value=&quot;i family&quot;&gt;&lt;br /&gt;&lt;br /&gt;
      &lt;input type=&quot;file&quot; name=&quot;img&quot; value=&quot;&quot;&gt;&lt;br /&gt;&lt;br /&gt;
      &lt;input type=&quot;submit&quot; value=&quot;go&quot;&gt;
  &lt;/form&gt;
  </code></pre>
  <p>and there is a controller:</p>
  <pre><code>namespace modules\families\controllers;
  use Craft;
  use craft\web\Controller;
  use craft\elements\Entry;
  class FamiliesController extends Controller
  {
      protected array|bool|int $allowAnonymous = true;
      public function actionStart() {
          $name = $this-&gt;request-&gt;getBodyParam('name');
          $img = $this-&gt;request-&gt;getBodyParam('img');
          $host = Craft::$app-&gt;request-&gt;hostInfo;
              $title = Entry::find()-&gt;section('familySeason')-&gt;title($name)-&gt;all();
              if(count($title) == 0){
                  $family = new Entry();
                  $family-&gt;sectionId = 7;
                  $family-&gt;enabled = false;
                  $family-&gt;title = $name;
                  $family-&gt;countFamily = &quot;test&quot;;
                  $family-&gt;imageFamily = $img;
                  $success = Craft::$app-&gt;elements-&gt;saveElement($family);
                  if (!$success) {
                      //Craft::error('Couldn’t save the review ID&quot;'.$id.'&quot;', __METHOD__);
                  }
              }
              $redirectUrl = $host.&quot;/contacts&quot;;
              Craft::$app-&gt;getResponse()-&gt;redirect($redirectUrl);
      }
  }
  </code></pre>
  <p>That's the problem- the imageFamilly field. This field is of the assets type. If I exclude it, then everything is fine, the element from the site side is saved and added to the system. However, with the construction that I described above, I get an error:</p>
  <pre><code>Unknown Property – yii\base\UnknownPropertyException
  Setting unknown property: craft\elements\Entry::imageFamilly
  </code></pre>
  <p>I need this field, I can't give it up. A picture of the family is needed.  What am I doing wrong? Tell me please. Thank you in advance.</p>
  
Tags: <craft3><assets><entry><form>
Title: How can I add an element with an image to a section from the site?
ThreadText: # How can I add an element with an image to a section from the site?
  
  (Asked by: username_0 on 2024-06-09)
  
  please tell me how to add an entry that contains an image to the desired section. I use Craft CMS 4.9.6. At the moment, I have a form on my website:
  
  ```
  <form method="POST">
      {{ csrfInput() }}
      {{ actionInput('families/families/start') }}
      <input type="text" name="name" value="i family"><br /><br />
      <input type="file" name="img" value=""><br /><br />
      <input type="submit" value="go">
  </form>
  
  ```
  
  and there is a controller:
  
  ```
  namespace modules\families\controllers;
  use Craft;
  use craft\web\Controller;
  use craft\elements\Entry;
  class FamiliesController extends Controller
  {
      protected array|bool|int $allowAnonymous = true;
      public function actionStart() {
          $name = $this->request->getBodyParam('name');
          $img = $this->request->getBodyParam('img');
          $host = Craft::$app->request->hostInfo;
              $title = Entry::find()->section('familySeason')->title($name)->all();
              if(count($title) == 0){
                  $family = new Entry();
                  $family->sectionId = 7;
                  $family->enabled = false;
                  $family->title = $name;
                  $family->countFamily = "test";
                  $family->imageFamily = $img;
                  $success = Craft::$app->elements->saveElement($family);
                  if (!$success) {
                      //Craft::error('Couldn’t save the review ID"'.$id.'"', __METHOD__);
                  }
              }
              $redirectUrl = $host."/contacts";
              Craft::$app->getResponse()->redirect($redirectUrl);
      }
  }
  
  ```
  
  That's the problem- the imageFamilly field. This field is of the assets type. If I exclude it, then everything is fine, the element from the site side is saved and added to the system. However, with the construction that I described above, I get an error:
  
  ```
  Unknown Property – yii\base\UnknownPropertyException
  Setting unknown property: craft\elements\Entry::imageFamilly
  
  ```
  
  I need this field, I can't give it up. A picture of the family is needed. What am I doing wrong? Tell me please. Thank you in advance.
  
  **Tags:** craft3, assets, entry, form
  
  
  ---
  
  ## 2 answers
  
  ### Answer by username_1 on 2024-06-10. Score: 1 | Accepted answer
  
  If your `imageFamily` field is an image field, you can't assign the POST value directly to the field. You need to first save the image as an asset, then assign the ID of the asset to the `imageFamily` field.
  
  Saving an uploaded image as a new asset requires a bit of boilerplate code. You can use the [`AssetsController::actionUpload` endpoint](https://github.com/craftcms/cms/blob/3fe8e67e1026084c282ced906617a78f175174f2/src/controllers/AssetsController.php#L227-L364) as a starting point. You need something like this (quick and untested, might need some adjustments):
  
  ```php
  use Craft;
  use craft\elements\Asset;
  use craft\helpers\Assets;
  use craft\web\UploadedFile;
  
  $uploadedFile = UploadedFile::getInstanceByName('img');
  $tempPath = $uploadedFile->saveAsTempFile();
  
  $volume = Craft::$app->getVolumes()->getVolumeByHandle('uploads');
  $folder = Craft::$app->getAssets()->ensureFolderByFullPathAndVolume('family-photos', $volume, false);
  
  $asset = new Asset();
  $asset->newFolderId = $folder->id;
  $asset->volumeId = $volume->id;
  $asset->tempFilePath = $tempPath;
  $asset->setFilename(Assets::prepareAssetName($uploadedFile->name)); 
  $asset->avoidFilenameConflicts = true;
  $asset->setScenario(Asset::SCENARIO_CREATE);
  
  Craft::$app->elements->saveElement($asset)
  
  ```
  
  Then once the asset was saved, you can assign it to your entry. A tiny gotcha is that the assets field expects an *array* of asset IDs and won't accept a single asset ID:
  
  ```php
  $family->setFieldValue('myCustomField', [$asset->id]);
  
  ```
  
  > **Comments:**
  > **username_0**: Ah , that is , the scenario is like this. First you need to upload an image, and then find it and assign it to the created record. It's clear. But where should I place the code you proposed? Sorry for the stupid question, I'm a beginner  
  > **username_0**: All I have now is one FamiliesController, which I described in my question and the form. Moreover, it works, but does not add images.  
  > **username_0**: or it can simply be supplemented directly in the  controller file FamiliesController?  
  > **username_1**: @username_0 You can do everything in one Controller action. Create the asset using the code above and validate that the asset was saved successfully (check the return value of `Craft::$app->elements->saveElement`, it will return `false` if an error occured). If everything is fine, proceed to create an entry and assign the new asset to the assets field.  
  > **username_0**: Thank you so much for your help... I'll try to do it later. I will write a little later whether I succeeded or not  
  > **username_0**: I tried to take your code and put it in my controller. I have deleted everything unnecessary. At the moment, the controller should only upload files to the "uploads" directory. But unfortunately the code gives an error: Unknown Property – yii\base\UnknownPropertyException Getting unknown property: modules\families\controllers\FamiliesController::volumes I thought it was because of the uploads directory. I checked it! The directory exists! What could be the reason?  
  > **username_0**: The error is currently in this line: $volume = $this->volumes->get volume by descriptor("downloads");  
  > **username_1**: @username_0 Ah, that was a leftover from my codebase. You need to use the `\Craft::$app` singleton to get the volumes and assets services. Updated in the code example above!  
  > **username_0**: Indeed! I have made corrections, there is no more error, but another one has appeared. I suspect it is related to the file name. Error: Invalid Configuration – yii\base\InvalidConfigException Asset not configured with its filename  
  > **username_1**: @username_0 Guess you need to explicitly set the filename. Updated the example code. Please note that it's only a starting point, you may need to customize this further and/or set additional properties.  
  > **username_0**: That's right, these are just the basic settings that allow you to upload a file. I made the latest corrections, the code is working. I think when creating this form, it is necessary to take into account the uniqueness of this file, the maximum weight of the image. What is the best way to check the weight of a file?  
  > **username_1**: You mean the file size? You can check the filesize on the original posted file or on the `UploadedFile` instance. But please create a new question for this, since it has not much to do with the original question. If your original problem is solved, don't forget to mark an answer as accepted.  
  > **username_0**: Yes, you have been very helpful in this matter, thank you. I put your answer as a solution. Regarding the weight of the file, I have created a separate question: https://craftcms.stackexchange.com/questions/41801/how-can-i-check-the-size-of-the-file-uploaded-via-the-form  
  
  ---
  
  ### Answer by username_2 on 2024-06-10. Score: 1
  
  You should be using the [`setFieldValue()`](https://docs.craftcms.com/api/v4/craft-base-elementinterface.html#method-setfieldvalue) method to set the value of a custom field, as documented at <https://craftcms.com/docs/4.x/extend/element-types.html#saving-custom-field-values>
  
  ```php
  $family->setFieldValue('myCustomField', $img);
  
  ```
  
  > **Comments:**
  > **username_0**: I replaced it, but the result remains the same. I get the same error: Unknown Property – yii\base\UnknownPropertyException Setting unknown property: craft\behaviors\CustomFieldBehavior::imageFamilly  
  > **username_0**: Although not. I had a typo. It was possible to send, but the picture was not added to the system. The imageFamily field in the system is empty  
  > **username_0**: $family->setFieldValue('imageFamily', $img);  
  > **username_0**: I came across an incomplete answer on the Internet that needs to be connected in my controller `use craft\web\UploadedFile;`  But I don't quite understand how to use it  
  
  ---
  
  