How can I change the checkboxlist to look similar to on/off switch? - yii

Is there any way to change the checkboxlist widget to look similar to the on/off switch presented in Kartik's Switch Input Widget, but in a group?
I'm using this code:
echo $form->field($model, 'blocked_list')->checkboxList($array_list);
Which is very simple to use, but produces "simple" list...
I've tried with Karitk's like this:
foreach ($array_list as $category_id=>$category_name) {
echo '<label class="control-label">' . $category_name . '</label>';
echo SwitchInput::widget([
'name'=>'blocked_list',
'value'=>in_array($category_id, $model->blocked_list),
'pluginOptions' => [
'size' => 'mini',
],
]);
But it does not link with the model, and the Form looses it format
Any ideas, please?

I've got it!
foreach ($category_array as $category_id=>$category_name) {
if ( isset($model->blocked_list[$category_id]) )
$model->blocked_list[$category_id] = true;
else
$model->blocked_list[$category_id] = false;
echo $form->field($model, 'blocked_list[' . $category_id . ']')
->label($category_name)
->widget(SwitchInput::classname(), []);
}
I just added a validate "if" to ask if the variable to display exists, and then set the correct value for the model
Hope it helps someone

Related

Shopify API getting order by name or order_number

Im using a plugin for CakePHP to make the calls to obtain certain orders. I can call all orders with certain fields, but I was wondering how would I have to make the call to get the orders with a certain name or order_number? Here is the source for the call to Shopify. Its already authenticated and everything:
public function call($method, $path, $params=array())
{
if (!$this->isAuthorized())
return;
$password = $this->is_private_app ? $this->secret : md5($this->secret.$this->ShopifyAuth->token);
$baseurl = "https://{$this->api_key}:$password#{$this->ShopifyAuth->shop_domain}/";
$url = $baseurl.ltrim($path, '/');
$query = in_array($method, array('GET','DELETE')) ? $params : array();
$payload = in_array($method, array('POST','PUT')) ? stripslashes(json_encode($params)) : array();
$request_headers = in_array($method, array('POST','PUT')) ? array("Content-Type: application/json; charset=utf-8", 'Expect:') : array();
$request_headers[] = 'X-Shopify-Access-Token: ' . $this->ShopifyAuth->token;
list($response_body, $response_headers) = $this->Curl->HttpRequest($method, $url, $query, $payload, $request_headers);
$this->last_response_headers = $response_headers;
$response = json_decode($response_body, true);
if (isset($response['errors']) or ($this->last_response_headers['http_status_code'] >= 400))
throw new ShopifyApiException($method, $path, $params, $this->last_response_headers, $response);
return (is_array($response) and (count($response) > 0)) ? array_shift($response) : $response;
}
private function shopApiCallLimitParam($index)
{
if ($this->last_response_headers == null)
{
return 0;
}
$params = explode('/', $this->last_response_headers['http_x_shopify_shop_api_call_limit']);
return (int) $params[$index];
}
...and the code that makes the GET call:
// I only want the id and title of the collections
$fields = "fields=name,id,status,financial_status,fulfillment_status,billing_address,customer";
// get list of collections
$custom_collections = $this->ShopifyAPI->call('GET', "/admin/orders.json", $fields);
$this->set('collections', $custom_collections);
I think I'm missing the place where I can put the conditions for the call to get certain orders. I've already read the API documentation but can't seem to get the answer.
I've tried putting the ?name=%231001 on the url after .json to try and get the order #1001, but it brings back a empty array.
Then I tried ?order_number=1001 but it brings me every order with as well 1001 D: This is really confusing, Could anyone help me?
Thanks in advance.
Well I found out that you can actually get the order using the name or order_number. Its another property that is not listed on the documentation for some reason. But in the URL, if your using another language, all you have to add in the GET is admin/order.json?name=%2310001&status=any this is to get the order 10001 so just add the order_number after the %23. I saw this on a forum in Shopify university, I was just implementing this wrong on my code. If your using the CakePhp shopify plugin like me all I did was add on the $field the ?name=%23". number ."&status=any";
Ill leave the code here:
$this->layout = 'main';
$order_number = "18253";
$fields = "name=%23". $order_number ."&status=any";
$order = $this->ShopifyAPI->call('GET', "/admin/orders.json", $fields);
if (!empty($order)) {
$this->set('order', $order);
} else {
$this->Session->setFlash('<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> No existe el numero de orden ingresado.','default',array('class' => 'alert alert-danger alert-dismissible', 'type' => 'alert'));
}
Hope this helps someone :P

Yii - disabling drop down when another is selected

So I have 2 $form->dropDownList
How can I make it in a way when if either one of the dropdown is selected, the other one gets set to value null and disabled, vice versa.
What options can I add into the array() so it behaves the way I want?
Please advise. Thanks in advance.
You need to handle it via javascript or jquery. First you should define an ID for two dropdowns in this way:
<?php echo $form->dropDownList($yourModel, 'attribute', CHtml::listData(...), array("id" => 'dropDown1')); ?>
<?php echo $form->dropDownList($yourModel, 'attribute', CHtml::listData(...), array("id" => 'dropDown2')); ?>
And in the script:
$(document).ready(function(){
if($("#dropDown1").val())
$("#dropDown2").attr("disabled", "disabled");
else
$("#dropDown2").removeAttr("disabled");
if($("#dropDown2").val())
$("#dropDown1").attr("disabled", "disabled");
else
$("#dropDown1").removeAttr("disabled");
$($("#dropDown1").on("change", function(){
if($(this).val())
$("#dropDown2").attr("disabled", "disabled");
else
$("#dropDown2").removeAttr("disabled");
});
$($("#dropDown2").on("change", function(){
if($(this).val())
$("#dropDown1").attr("disabled", "disabled");
else
$("#dropDown1").removeAttr("disabled");
});
});

Cake PHP Update single fields in View - Undefined Variable

i search a long time, but i dont find a solution for my problem.
The case is, that i have a few buttons integrated in my view and clicking on them affected updating single input fields. The problem is that i have warnings, that variables are undefined in view. I understand why and how i suppress them, but i`m not sure, if this is a good solution. Is there a better way to solve this? What is best practice?
Here is my code from the view file:
<?php
echo $this->Form->create('Excel', array('type' => 'file'));
echo $this->Form->file('File');
echo $this->Form->submit('Upload xls File');
echo $this->Form->end();
echo $this->Form->create('Config');
//echo $this->Form->input('Name');
echo $this->Form->input('vlanNumber');
echo $this->Form->input('description', array('value' => $description));
echo $this->Form->input('preSharedKey', array('value' => $preSharedKey));
echo $this->Form->button('generate', array('name'=>'generateButton'));
echo $this->Form->input('customerPeerIp', array('default' => 'id_of_default_val','value' => $cusPeerIp));
The generate button affect a new preSharedKey. And the upload of the csv affected an update of the other fields.
The relevant code of the controller is this:
public function inputData() {
if ($this->request->is('post')) {
$post_data = $this->request->data;
if (isset($this->request->data['show'])) { //Submit Button was clicked
$this->Session->write('Configuration',$post_data); //Store the input fields in the session
return $this->redirect(array('action' => 'showPreview'));
} else if (isset($this->request->data['cancel'])) { // Cancel button was clicked: Go back to index site
return $this->redirect(array('action' => 'index'));
} else if (isset($this->request->data['generateButton'])) {
return $this->set('preSharedKey', $this->getRandomString(20)); //Set a Pre Shared Key with 30 signs
}
if (!empty($this->data) && is_uploaded_file($this->data['Excel']['File']['tmp_name'])) {
$this->importData($this->data['Excel']['File']['tmp_name']);
$excel=new Excel();
$values=$excel->getParams($this->data['Excel']['File']['tmp_name']);
$this->set('description',$values['description']);
$this->set('cusPeerIp',$values['cust_peer']);
return;
//this calls the Excel Class function
}
//print_r($post_data);
//echo $post_data['Config']['Name'];
//echo $this->request['Config']['task_1'];
}
$this->set('description','');
$this->set('cusPeerIp','');
$this->set('preSharedKey', '');
}
Can you please help me?

Display images from protected folder

I have a protected folder within Yii and I'm looking to display some of those images within the site. I've tried the following code and it works within the site/index controller in that it returns just the image I wanted.
However when I tried to separate the code it didn't work. Any help is appreciated.
Model
public function getImage() // will take file identifier as #param
{
$imageID = '2562584569'; // will eventually be dynamically assigned
$image = Images::model()->find('tmp_name=:id', array('id' => $imageID));
$dest = Yii::getPathOfAlias('application.uploads');
$file = $dest .'/' . $image->tmp_name . '.' . $image->extension;
if(file_exists($file)){
ob_clean();
header('Content-Type:' . $image->logo_type);
readfile($file);
exit;
}
}
And in the view
CHtml::link('<img src="' . Yii::app()->request->baseUrl .'/images/image" />', array('product/index', 'id'=>$data['product_id'], 'slug'=> $data['product_slug']));
Thanks
Jonnny
"protected" folder are not accessible from the client browser. This prevents people to have access to important files, like your source code.
If you want to store images inside "protected" and want them to be accessible, you need to publish them using CAssetManager.
Usage is something like:
$path = Yii::app()->basePath.'/path-inside-protected';
$yourImageUrl = Yii::app()->assetManager->publish($path);
Yii will then use the file as an asset, coping it to the "assets" folder, sibling to "protected". After that, you can just use the url returned on your HTML.
<img src="<?php echo $yourImageUrl ?>">
I went about it like this
CHtml::link('<img src="' . $this->createUrl('/images/image', array('data'=>$data['data'])) . '" />', array('product/index', 'id'=>$data['product_id'], 'slug'=> $data['product_slug']));
Model
public function actionImage($data)
{
$image = Images::model()->find('tmp_name=:data', array('id' => $data));
$dest = Yii::getPathOfAlias('application.uploads');
$file = $dest .'/' . $image->tmp_name . '.' . $image->extension;
if(file_exists($file)){
ob_clean();
header('Content-Type:' . $image->logo_type);
readfile($file);
exit;
}
}
Thanks for all help

DropDownList won't POST value by using ajax

I created DropDownList and I'm trying to fill div with content and I know how to do it. But problem is that my dropdown list won't POST value.
This is code from view\index.php
<?php
echo CHtml::dropDownList('parovi', '', $model->dropDownListParovi(), array
(
'class'=>'dropDownListLegloIzaberiPar',
'empty'=>array('-'=>Yii::t('default', 'PAR_UZGOJNI_DNEVNIK_LEZENJA_IZABERI_PAR')),
'ajax'=>array
(
'type'=>'POST',
'url'=>Yii::app()->createUrl('/paruzgojni/ajaxIzlistajLegla'),
'update'=>'#legla',
),
)
);
?>
<div id="legla"></div>
And this is from controller
public function actionAjaxIzlistajLegla()
{
echo $_POST['parovi'];
}
this AjaxIzlistaijLegla action is inside accessRules(). And it's working cause When I replace echo $_POST['parovi']; with echo "Hello"; it works, it updates my div. But I don't know why it won't POST that value from drop down list.
jquery is included in head.
Answer is I should wrap my dropDownList with CActiveForm like this
$this->beginWidget('CActiveForm', array(
'id'=>'par-uzgojni-ispis-legla-form',
));
echo CHtml::dropDownList('parovi', '', $model->dropDownListParovi(), array
(
'class'=>'dropDownListLegloIzaberiPar',
'empty'=>array('-'=>Yii::t('default', 'PAR_UZGOJNI_DNEVNIK_LEZENJA_IZABERI_PAR')),
'ajax'=>array
(
'type'=>'POST',
'url'=>Yii::app()->createUrl('/paruzgojni/ajaxIzlistajLegla'),
'update'=>'#legla',
),
)
);
$this->endWidget();
Because I didn't wrap it, it couldn't POST any data to my controller