Skip to content
Advertisement

yii2 php set model attribute when clicking submit button

I have a view with a form in which I have users fill in attributes of the model. When submitting, I want the users to have the possibility to either publish the model or to save it as a draft. The difference basically only is a boolean “draft” that needs to be set in the database.

<?= Html::submitButton(Yii::t('OfferModule.form', 'Save as draft'), ['class' => 'btn btn-outline btn-submit', 'id' => 'draft-btn']) ?>
<?= Html::submitButton(Yii::t('OfferModule.form', 'Submit'), ['disabled' => 'disabled', 'class' => 'btn btn-primary btn-submit', 'id' => 'submit-btn']) ?>

As I am usually developing with JavaScript and only got the php basics so far, what would be the best way to do this? The solutions that I can come up with are:

a) send an additional param to the Controller, and set the model value according to it in the Controller (-> how would I send another param additionally to the model?)

b) set the attribute “draft” when clicking on the button to save as draft before submitting (-> is there a possibility to set an attribute and submit with the same button?)

c) hide a checkbox behind the “save as draft” button and when clicking on it, trigger the submission by adding some JavaScript (-> how would I hide the checkbox form field behind a button?)

I would be really grateful if someone could help me out here 🙂 Thanks in advance!

Advertisement

Answer

You can submit the form using like:

<button type="submit" id="draft-btn" value="draft" name="actionBtn">Save as draft</button>
<button type="submit" id="submit-btn" value="submit" name="actionBtn">Submit</button>

You can decide whether to save as draft or publish by the actionBtn value. If the value of ‘actionBtn’ is draft then save it as draft and when the value is submit then publish it.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement