1

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.

2 Answers 2

1

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 as a starting point. You need something like this (quick and untested, might need some adjustments):

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:

$family->setFieldValue('myCustomField', [$asset->id]);
13
  • 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
    – Dimi
    Commented Jun 10 at 14:10
  • All I have now is one FamiliesController, which I described in my question and the form. Moreover, it works, but does not add images.
    – Dimi
    Commented Jun 10 at 14:13
  • or it can simply be supplemented directly in the controller file FamiliesController?
    – Dimi
    Commented Jun 10 at 14:22
  • @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.
    – MoritzLost
    Commented Jun 10 at 14:22
  • 1
    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: craftcms.stackexchange.com/questions/41801/…
    – Dimi
    Commented Jun 19 at 9:28
1

You should be using the 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

$family->setFieldValue('myCustomField', $img);
4
  • 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
    – Dimi
    Commented Jun 10 at 13:19
  • 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
    – Dimi
    Commented Jun 10 at 13:24
  • $family->setFieldValue('imageFamily', $img);
    – Dimi
    Commented Jun 10 at 13:25
  • 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
    – Dimi
    Commented Jun 10 at 13:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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