Yii2: How to show checked values in CheckboxList - php

I want to show checked values in my checkboxlist in Yii 2.0. Following is my code:
Main Array:
<?php
$featureArr = array(
'Change Requester' => 'Change Requester',
'Clone Request' => 'Clone Request',
'Suspend Request' => 'Suspend Request',
'In-Process Requests Open in Edit Mode' => 'In-Process Requests Open in Edit Mode',
'Allow On-the-Fly Notifications' => 'Allow On-the-Fly Notifications',
'Additional Comments Field' => 'Additional Comments Field',
'Do Not Validate Draft Requests' => 'Do Not Validate Draft Requests',
'(Web-Only) Allow File Attachments' => '(Web-Only) Allow File Attachments',
);
Getting data from table to display checked items:
$formFeatureModel = FormFeatureForm::find()->where("form_id=" . $model->id)->all();
$checkedFeatureArr = array();
foreach ($formFeatureModel as $data) {
$checkedFeatureArr[$data->feature] = $data->feature;
}
?>
Checkbox field
<?= $form->field(new FormFeatureForm, 'feature')->checkboxList($featureArr, ['class' => 'featureCls']) ?>
I am getting checked item in $checkedFeatureArr from database. Now I just want to show checked items. So, Where should I pass $checkedFeatureArr array? Getting stuck in this.
Any help would be appreciated.

When using it with model, you should fill feature model property with selected values instead.
$model->feature = $checkedFeatureArr;
Then it will be checked automatically.
Additional tips:
It's better avoid concatenation in SQL, replace ->where("form_id=" . $model->id) with ->where(['form_id' => $model->id]).
It's better create ActiveForm before rendering ActiveField.

Related

Default value in ActiveDropDownList

I've inherited a piece of code from an old developer and currently trying to figure out the method behind how it submits.
I'm currently trying to get a quick fix in place where I hide one of his fields to get the form submitting, the issue I'm having is that I can't seem to set the dropdownlist to a default value, which should be United Kingdom, with the id 826 in the database.
echo CHtml::ActiveDropDownList($address, 'country_id', CHtml::listData(Country::model()->findAll(), 'id', 'name', 'continent'), array(
'class' => 'col-md-5 hidden',
'prompt' => 'Select Country',
'label' => 'something here',
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('/user/UpdateRegions'),
'dataType' => 'json',
'data' => array('country_id' => 'js:this.value', 'YII_CSRF_TOKEN' => Yii::app()->request->csrfToken),
'success' => 'function(data) {
$("#Address_country_region_id").html(data.country_id);
$("#Address_country_region_id").removeClass(\'hidden\');
if($("#venue_id").val() === "") {
$("#Address_country_region_id").addClass(\'hidden\');
}
}',
)));
$path = CController::createUrl('/admin/user/UpdateRegions');
$id = $address->id;
// On Load
Yii::app()->clientScript->registerScript('ready', '
$.ajax({
type: \'POST\',
dataType : \'json\',
data: {\'country_id\': $(\'#Address_country_id\').val(), \'update_id\' : "' . $id . '"},
url: "' . $path . '",
success: function(data){
$(\'#Address_country_region_id\').html(data.country_id);
}
})
');
How do I get this dropdownlist pointing towards the country_id of 826 as the page loads so I can hide the field and pass the validation of the form.
regards.
this code you pasted does this:
the first part renders a dropdown which does an ajax request on change to /user/UpdateRegions to fill the dependent dropdown for the regions.
the second part does also an ajax request when the page is "ready". So that the region select is filled when the page is ready.
Your script should output the id 826 if you printout the current set id.
If not the value isn't correctly set to the address model.
echo $address->country_id;
If you want to set the default value you can do this at multiple places. e.g. in the controller 'before' the actual submitted value is set or in the model code itself (depends on your code e.g. if you have an additional form model which is extended from your activerecord model).
The correct line in your controller could be before something like this:
$address->country_id= 826;
before one of these lines in your controller
$address->attributes=Yii::app()->request->getQuery(get_class($address));
or
$address->attributes=Yii::app()->request->getPost(get_class($address));
or
$address->attributes=$_POST['address']; // or $_GET
If you have difficulties to find the correct position post some controller code.
I guess you could find some help also here
Yii 1.1: An Easy Solution for Dependent dropDownList Using AJAX
To set default value for $address model, put
$address->country_id = Yii::app()->request->getParam(get_class($address).'[country_id]', 816);
before
echo CHtml::ActiveDropDownList($address, 'country_id', CHtml::listData(Country::model()->findAll(), 'id', 'name', 'continent'), array(

is it possible to display content from cgridview to dropdown in yii?

I have modified my model so that the data displayed in cgridview is unique per user, depending on the account type...
However I need to create a form from another model where I could get the data from the cgridview via dropdown...
I used this code at first...
<?php
$this->widget('ext.select2.ESelect2',array(
'model'=>$model,
'attribute'=>'pr_id',
'data'=>$model->searchPatient(),//function to provide data
// or
//'data'=>CHtml::listData(PatientRecord::model()->findAll(), 'id', 'first_name')
);
?>
but it returns all of the contents of the PatientRecord model, I tried using a condition before planning to retrieve the contents from the cgridview...
$doctor= Yii::app()->user->id;
CHtml::listData(PatientRecord::model()->findAll( array(
'condition'=>'doctor_id=:doctor_id',
'params' => array(':doctor_id' => $doctor)
)
);), 'id', 'first_name')
it didn't have an error but it didn't display anything on the dropdown either...
any suggestions?
I think the problem is with a ; and ) in your model code, try this:
$doctor= Yii::app()->user->id;
CHtml::listData(PatientRecord::model()->findAll( array(
'condition'=>'doctor_id=:doctor_id',
'params' => array(':doctor_id' => $doctor)
)
), 'id', 'first_name');
You should always enable error logging in local environment, this will help you find any errors in your code. Here is a link on how to enable error logging.
Hope that helps :)

Getresponse API 2 (Adding Custom fields and contacts using PHP)

Im new to coding and web development as it is and diving into the deep end with API's is a thing i wish i never had done! However being said i have progressed further than expected. I am now having problems when trying to add custom fields to the add contact feature. Im trying to get the code to add the hidden form input fields when the user hits my thankyou page. I dont want to use Getresponses own Form builder for my main page so it was better to use the API. I have the code running perfectly when it comes to just adding the contact however when i add the set_contact_customs the code does not execute and fails with the following error: (Request have return error: Array) So i understand its to do with the set_contact_customs array however im clueless as to what it is i have done wrong.. Any advice and help is greatly appreciated as i am still learning the basics so picking up on what you experts say is a great learning curve. Thanks.
--- Below is the working version without the set_contact_customs ----
<?php
// Add contact to selected campaign id
try{
$result_contact = $client->add_contact(
$api_key,
array (
'campaign' => 'My-Camp-ID',
'name' => $fullname,
'email' => $emailaddress
)
);
echo "<p style='color: blue; font-size:24px;'>No Errors, Contact and Custom Fields have been added...</p>";
}
catch (Exception $e) {
echo $e->getMessage();
}
?>
--- Here is the code that causes the problems (with set_contact_customs) ----
<?php
// Add contact to selected campaign id
try{
$result_contact = $client->add_contact(
$api_key,
array (
'campaign' => 'My-Camp-ID',
'name' => $fullname,
'email' => $emailaddress
)
);
$result_contact = $client->set_contact_customs(
$api_key,
array(
'Survey Type' => $surveytype,
'Survey Cost' => $surveycost
)
);
echo "<p style='color: blue; font-size:24px;'> Contact Added </p>";
}
catch (Exception $e) {
echo $e->getMessage();
}
?>
API 2 doesn't really exist: in GetResponse they say version "1.5.0 - this is last JSON/RPC version of our API", especially if you were speaking 10 months ago. Now they are preparing to beta-test v3. So I will assume you were speaking about 1.5 and answer about it (I'm not familiar with v3, maybe there it's different).
You must send contact id with set_contact_customs, and you didn't.
When it says, "request error: array", it doesn't relate to your array (even though the problem is in your array, because you don't send in it contact id), they are sending an array as a response with error messages.
I'd love to tell you, where to get the contact id in order to send it, but I'm looking for it myself now. :)
UPDATE:
Ok, I combined it from pieces all over the internet, and now here's the working format.
You don't need to add_contact and then update it, you can do it in one go, adding the 'customs' parameter to the add_contact call (GR say, that we shouldn't expect for the contact to be added immediately, so you might not even get whom to update, if you call that function right away).
The fields for add_contact are described here.
The 'customs' parameter should look differently. Instead of:
array(
'Survey Type' => $surveytype,
'Survey Cost' => $surveycost
)
it should be:
array(
array( 'name' => 'Survey Type', 'content' => $surveytype ),
array( 'name' => 'Survey Cost', 'content' => $surveycost )
)
By the way, from what I tested, - blessedly, you don't need to define in GR UI those custom fields first, whatever you send, will be added or updated (in their limits for the custom field names and values).
I got error, when tried to send one custom field with empty content, when calling add_contact. When I sent it with set_contact_customs, I didn't get any error; I wanted to see, if it would delete the field or field value - it didn't do a thing.
If you still wish to update the existing contact, here's how to send the contact id with the update call:
$result = $client->set_contact_customs(
$api_key, array(
'contact' => $contact_id,
'customs' => $custom_fields_array
)
);
To first find contact id, you should call get_contacts. And since it's been said (I haven't tested it), that in different campaigns contacts with the same email address have different contact id, you should pass both the campaign, and the email with it.
As you can see, campaign can be sent in 'campaigns' parameter (then campaign id, that you got for add_contact, should be used), or in 'get_campaigns' (then the campaign name or even prefix can be used).
Here's the call with campaign id, for your code:
$result = $client->get_contacts(
$api_key, array(
'campaigns' => array( 'My-Camp-ID' ),
'email' => array( 'EQUALS' => $emailaddress )
)
);
To retrieve contact id from get_contacts, do the same as recommended for retrieving campaign id:
$contact_id = array_pop( array_keys( $result ) );
if ( empty( $contact_id ) ) {
//still not ok
}
else {
//you can call set_contact_customs
}
In order for that error message to be more descriptive, instead of just 'Request have return error: Array', open your jsonRPCClient.php, which you most surely include in your file with these GR function calls, and look for the following line:
!is_null($response['error']) => 'Request have return error: ' . $response['error'],
and replace it with the following, at least:
!is_null($response['error']) => 'Request have returned error: ' . var_export($response['error'], true),
Now your code will use the beloved var_export function and if you make a mistake, you will see in your error log something like:
Request have returned error: array (
'message' => 'Invalid params',
'code' => -32602,
)
I dedicate this thorough answer to all those, who helped me endlessly here on StackOverflow, just giving their answers to someone else's questions, sometimes years ago. Thank you! Hopefully my answer will save someone time, efforts, and mood, too. :)

How to pass array values to controller for validation?

I am trying to pass the values of form inputs to a controller for validation. The values are populated in the view using an array. The problem is that I don't know how to get the necessary 'name' values from the array for the individual inputs in order to pass them through validation.
In the first view the form inputs are described this way:
<?php echo form_checkbox('study_items[]', 'Medical History', FALSE);
echo form_label('Medical History', 'Medical History');?>
<br>
<?php echo form_checkbox('study_items[]', 'Physical Exam', FALSE);
echo form_label('Physical Exam', 'Physical Exam');?>
<br>
<?php echo form_checkbox('study_items[]', 'Clinical Assessment', FALSE);
echo form_label('Clinical Assessment', 'Clinical Assessment');?>
The user only has to check the item(s) that apply to their specific need. This is submitted to the validation controller which, after successful validation, ONLY sends those items that were selected back to a view in an array like so:
$data['si_items'] = $this->input->post('study_items');
In the next view, the code for a sample input looks like this:
<?php foreach ($si_items as $si_item) {
echo $si_item. ' '. "$";
$data001 = array(
'name' => $si_item,
'id' => $si_item,
'value' => '',
'maxlength' => '10',
'size' => '50',
'style' => 'width:100px',
);
echo form_input($data001);
echo '<br>';
}
?>
and allows the user to enter a dollar amount for the items they selected to fit their need on the previous page.
As sample output of this portion of the code looks like this:
"Medical History $_______________"
"Physical Exam $_______________"
"Clinical Assessment $_______________"
where the blank is a textbox for entering the price of each item. So far, this all works perfectly to display each form input box and labels checked by the user in the previous view.
However, I'm at a loss as to how to get the 'name' for each individual input in order to validate it. The validation controller does not recognize '$si_items' as a name value. This has me stumped and there HAS to be a way to do this.
In my validation controller I want to check that each entry has a decimal value (i.e. 234.56) as the user's input.
Any ideas? Is there a more efficient way to do this?
we are missing swaths of code, but from what you have shown;\
$data['si_items'] = $this->input->post('study_items');
is the assignment of your study items (which is an array), meaning that the call in your foreach should not be
foreach ($si_items as $si_item) {
but rather
foreach ($data['si_items'] as $si_item) {
that or change your initial assignment to the following;
$si_items = $this->input->post('study_items');

CodeIgniter - form_checkbox and a required check

I have a little checkbox on a signup form im creating which 'must' be checked before the user is allowed to continue ... Im finding it difficult to figure out how to do this with the form_validation functions as well, basically the 'agree to terms and conditions' checkbox MUST be checked in order for the user to continue, if not, an error message displayed, the code i have at the moment is below, if someone could give me a bit of a helping hand that would be great.
Ok, in my view i have the following
$agreeCheck = array( 'name' => 'agreeCheck', 'id' => 'agreeCheck', 'value' => 'agree', 'checked' => set_checkbox('agreeCheck', 'agree', FALSE));
<?php echo form_checkbox($agreeCheck); ?>
and then in my controller i have the following
$this->form_validation->set_rules('agreeCheck', 'Agree to the Terms and Conditions', 'required');
At the moment, it only remembers the value that was clicked if there is a submission, except if its not checked, it doesnt return anything.
Try this out:
$this->form_validation->set_rules('agreeCheck', 'Agree to the Terms and Conditions', 'required|isset');
Try this out:
$this->form_validation->set_rules('agreeCheck', '...', 'callback_terms_check');
And then set up this method in the controller:
function terms_check() {
if (isset($_POST['agreeCheck'])) return true;
$this->form_validation->set_message('terms_check', 'THIS IS SOOOOO REQUIRED, DUDE!');
return false;
}

Categories