how to write proper query in cakephp 3.7 to get the data of a column and display list of items in a drop down - cakephp-3.x

I am trying to fetch the list of city_name (column) from my table Cities and display that list into my dropdown
I write the following code in my controller method
namespace App\Controller;
use App\Controller\AppController;
class PrimeUsersController extends AppController
{
public function initialize()
{
parent::initialize();
$this->viewBuilder()->setlayout('primewishsLayout');
$this->loadModel("Cities");
$this->loadModel("States");
$this->loadModel("Users");
}
public function addnew()
{
// $this->autoRender=false;
$this->set('title',"Add User/Company");
$digits_needed=10;
$random_number=''; // set up a blank string
$count=0;
while ( $count < $digits_needed )
{
$random_digit = mt_rand(0, 9);
$random_number .= $random_digit;
$count++;
}
$this->set("rendomReg",$random_number);
// $view=$this->States->find()->toArray();
// print_r($view);
// city list
$fieds = array('Cities.city_name');
$city = $this->Cities->find()->select(['city_name'])->enableHydration(false)->toList();
// print_r($city);die;
$this->set(compact('city'));
}
}
and this is my dropdown where I want to show my item list in addnew.ctp
<div class="col-md-3 pl-1">
<div class="form-group">
<label>City:</label>
<?php
echo $this->Form->control('City',array(
'options' => $city,
'value'=>$option,
'required'=>'required',
'class'=>'form-control',
'label'=>false,
'default' => $option['select']
));
?>
</div>
</div>
I am able to fetch the list but when I click on dropdown the list display like this:-
1
Kanpur
2
Lucknow
3
Delhi
please help me out..

According to Cakephp
CakePHP provides a simple to use method for generating ‘lists’ of
data. It is often useful to generate an associative array of data from your application’s data. For example, this is very useful when creating elements.
So to get the list of cities you can use list in your find query. This will give you an associative array of id and city name from your cities table.
PrimeUsersController.php
$city = $this->Cities->find('list')->find('list', [
'keyField' => 'id', // specify column name that you used used as city id in cities table
'valueField' => 'city_name' // specify column name that you used used as city name in cities table
])->toArray();
$this->set(compact('city'));
addnew.ctp
$this->Form->select(
'city',
$city,
['required'=>'required',
'class'=>'form-control',
'label'=>false,
'empty' => 'Select City']
);
Cakephp -> Retrieving Data & Results Sets -> Finding Key/Value Pairs
Hope this will help!

Try something like this:
$this->Form->select(
'city',
$city,
['required'=>'required',
'class'=>'form-control',
'label'=>false,
'default' => ':Select:']
);
More instructions: https://book.cakephp.org/3.0/en/views/helpers/form.html#common-options-for-specific-controls

Related

cscart {{o._tax_name}} value in documents - invoice and order summary

I wish to add more values to product table in cs- cart documents.
In my country we have requirements for tax name for each product included in invoice.
How can I add value of {{o._tax_name}} into product table in documents invoice and order summary in cscart ?
You could modify or add inside your own addon at path:
/app/addons/my_changes/schemas/snippets/order_products_table.post.php
the code that looks something like this:
$schema['custom_tax_name'] = array(
'class' => '\Tygh\Template\Document\Variables\GenericVariable',
'data' => function (\Tygh\Template\Snippet\Table\ItemContext $context) {
$data = array();
$product = $context->getItem();
$data['tax_name'] = getTaxName($custom_val); //you could have function here to get whatever your needs are
return $data;
},
'arguments' => array('#context', '#config', '#formatter'),
'attributes' => array(
'tax_name'
)
);
After this, clear your cache and then you will see inside Menu: Documents - order.invoice the new value that already created, like this:
{{ custom_tax_name.tax_name }}

Laravel select dropdown using ajax

I have data in an array that contains hotels' names with their id. I want to place them in my select where I will display only the city an grab the id to do ajax and display rooms name. The problem is it is displaying both the name of the hotel and the id array in my dropdown.
this is my controller.
foreach ($hotel as $nam ){
$hotel_nam[]=$nam->id;
$hotel_nam[]=$nam->hotel_name;
}
return $hotel_nam;
this is my drop down
{!! Form::select('hotel_name',$hotel_nam,'S', array('style'=>' Border:none; ', 'id' => 'hotel_id', 'onchange'=>"showRooms(this.value)"));!!}
$hotelLists = [''=>'--Select Hotel--'];
foreach ($hotel as $nam) {
$hotelLists[$nam->id] = $nam->hotel_name;
}
{!! Form::select('hotel_name',$hotelLists,'', array('style'=>' Border:none; ', 'id' => 'hotel_id', 'onchange'=>"showRooms(this.value)"));!!}

Load cities from state laravel

I am working with laravel, right now, i am making an user registry Form, i am relating the state and its cities, so, i need to change a select field values according the state that user chooses.
I have something in the form:
{{ Form::select('city', $city, array('id', 'city')}}
If i use the {{Form::select}} fields in conventional way it charges all the cities from one state, so, when the user select a state, it must change the list of cities in the select field.
I searched but i didn't find any. How can i do that?
thanks.
You can use ajax with jQuery.
In your view set an event when the state change, like this:
$(document).on('change', '#state_id', function (e) {
// empty the select with previous cities if we have.
$('#cities').empty();
$.ajax({
type: "POST",
dataType: "json",
// actions is a controller
// cities is a method of actions controller
url : "{{ URL::to('actions/cities') }}",
//here we set the data for the post based in our form
data : $('#MyFormID').serialize(),
success:function(data){
if(data.error === 0 ){ // all was ok
for (var i = 0; i < data.cities.length; i++) {
$('#cities').append("<option value='"+data.cities[i].id+"'>"+data.cities[i].city_name+"</option>")
}
}else{
alert(data);
}
},
timeout:10000
});
});
actions/cities controller
//remember, this is a post method
public function postCities(){
// validate
$validator = Validator::make(Input::all(),
array(
'state_id' => 'required|integer'
));
if ($validator->fails()) {
return Response::json(array('error' => 1, 'message' => 'State is required'));
}
//City is your model, I assumes that you pkey is ID and the city name is city_name and your fkey is state_id
$cities = City::where('state_id', '=', Input::get('state_id'))->get();
return Response::json(array('error' => 0, 'cities' => $cities));
}
public function getCities($province_id)
{
$cities = Cities::where('province_id', '=', $province_id)->get(['id', 'name']);
return Response::json(array('error' => 0, 'cities' => $cities));
}
You might want to check a sample vue component that ships with my package Laravel Cities that performs exactly what you are trying to build.
This is a simple package that allows you seed localy all the cities of any country on the world (provided by geonames.org) and perform any query with the provided Eloquent model. It exposes an HTTP API and a vue component that allows you to select any city through a series of steps.
You can insert it in your forms like any other input field:
<form action="post-url" method="POST">
<geo-select></geo-select>
<!-- Add more form fields here... -->
<input type="submit">
</form>
With the provided Eloquent model You can perform queries like this:
// Get the States of USA in aplhabetic order
Geo::getCountry('US')
->children()
->orderBy('name')
->get();
Sorry, no demo yet, but you can check some sceenshots on the github page...

How to find a list of editable attributes in a class - Magento

When creating a product I can use the following via the API:
$newProductData = array(
'name' => (string)$stockItem->STOCK_DESC,
'websites' => array(1,2), // array(1,2,3,...)
'short_description' => (string)$stockItem->STOCK_DESC,
'description' => (string)$stockItem->LONG_DESC,
'status' => 1,
'weight' => $stockItem->WEIGHT,
'tax_class_id' => 1,
'categories' => array(3108),
'price' => $stockItem->SELL_PRICE
);
$my_set_id = 9; // Use whatever set_id you want here
$type = 'simple';
$mc = new Mage_Catalog_Model_Product_Api();
$mc->create($type, $my_set_id, $stockItem->STOCK_CODE, $newProductData);
When I look into the $mc->create call I see that it does this:
foreach ($product->getTypeInstance(true)->getEditableAttributes($product) as $attribute) {
}
which indicates there is a list of attributes which can be edited against an object.
How do I find these? Is there a specific place this information is found?
Edit: I just did:
Mage::log($product->getTypeInstance(true)->getEditableAttributes($product));
and had a look at the results. It seems all the editable attributes are there which can be found under [attribute_code] => but I would still like a better method of knowing where to look to get this list.
This will depend entirely on the attribute set of the product you're trying to edit, and the configuration of each individual attribute. There's no place in the UI that will list these attributes out for you. Your best bet is to run some custom code for your product
$product = Mage::getModel('catalog/product')->load($product_id);
foreach ($product->getTypeInstance(true)->getEditableAttributes($product) as $code=>$attribute)
{
var_dump($code);
}
Here's how to track this information down. If you jump to the getEditableAttributes method
#File: app/code/core/Mage/Catalog/Model/Product/Type/Abstract.php
public function getEditableAttributes($product = null)
{
$cacheKey = '_cache_editable_attributes';
if (!$this->getProduct($product)->hasData($cacheKey)) {
$editableAttributes = array();
foreach ($this->getSetAttributes($product) as $attributeCode => $attribute) {
if (!is_array($attribute->getApplyTo())
|| count($attribute->getApplyTo())==0
|| in_array($this->getProduct($product)->getTypeId(), $attribute->getApplyTo())) {
$editableAttributes[$attributeCode] = $attribute;
}
}
$this->getProduct($product)->setData($cacheKey, $editableAttributes);
}
return $this->getProduct($product)->getData($cacheKey);
}
You can see that this method gets a list of all the attributes set on a particular product.(i.e. All the attributes that are a member of the product's attribute set). Once it has this list, it goes through each and checks if its apply_to property matches the type id of the current product.
The Apply To attribute is set at
Catalog -> Attributes -> Manage Attributes -> [Pick Attribute]
This form field updates the database table catalog_eav_attribute. If you run the following query you can see examples of this value as is stored
select attribute_id, apply_to from catalog_eav_attribute where apply_to is NOT NULL;
75 simple,configurable,virtual,bundle,downloadable
76 simple,configurable,virtual,bundle,downloadable
77 simple,configurable,virtual,bundle,downloadable
78 simple,configurable,virtual,bundle,downloadable
79 virtual,downloadable
So, get your product's attribute set. Get a list of attributes in that set. Compare the value of the attribute's apply_to field vs. the value of your product's type_id. That will let you build a list of these attributes.

where to add- class="required" (jquery validation) in form_dropdown?

I have a dropdown list which is being populated from database. It is working fine but in the form_dropdown in the view file, I want to add class="required" for validating the dropdown using Jquery. I have tried to make it work but as it turned out it won't work. Would you please kindly help me where exactly to put the class="required" - and make the jquery validation work?
Thanks in Advance
I have this in my controller
// To get the batch name
$this->load->model('dropdown_batchlist');
$data['dropdown_batchlist']= $this->dropdown_batchlist->dropdown_batchlist();
this in my model-
function dropdown_batchlist() {
$this->db->select('batchname, batchid');
$records=$this->db->get('batch');
$data=array();
// add it here as the first item in the array,
// assuming you don't have a $row->batchid of 0 in your results.
$data[0] = 'SELECT';
foreach ($records->result() as $row)
{
$data[$row->batchid] = $row->batchname;
}
return ($data);
}
And this in my view file
<?php echo form_dropdown('batchid', $dropdown_batchlist,'', 'class="required"' ); ?>
The Problem is Solved
I have figured out the problem. The view file was okay, all I had to do is replace $data[0] = 'SELECT'; with
$data[' '] = 'SELECT';
Thanks
Try setting the attributes using an associative array:
$attributes = array(
'name' => 'batchid',
'class' => 'required',
'options' => $dropdown_batchlist
);
echo form_dropdown($attributes);

Resources