I know there are lots of tutorials on loads of sites (I have read most of them in the last few hours) but I still can not get the following code to work. Can anyone see what I am doing wrong?
The second select box does not update when I change a value in the first one and I don't get the blue spinning ajax circle next to the first select box when I make a change.
$form['age_range'] = array(
'#type'=>'select',
'#title'=>'Age Range',
'#options'=>$age_ranges,
'#ajax'=>array(
'event'=>'change',
'callback'=>'childcare_observations_ajax_set_eyfs_category_list',
'wrapper'=>'eyfs_category_wrapper',
'method'=>'replace',
)
);
$form['eyfs_category_wrapper'] = array('#prefix'=>'<div class="eyfs_category_wrapper">','#suffix'=>'</div>');
$form['eyfs_category_wrapper']['eyfs_category'] = array(
'#type'=>'select',
'#title'=>'EYFS Category',
'#options'=>array(1=>'one',2=>'Two'),
);
return $form;
}
function childcare_observations_ajax_set_eyfs_category_list($form,&$form_state){
$eyfs_category_options = array();
$eyfs_category_options[0] = "We just changed the list values";
$eyfs_category_options[1] = "We also added a second option";
$form['eyfs_category_wrapper']['eyfs_category'] = array(
'#type'=>'select',
'#title'=>'EYFS Category',
'#options'=>$eyfs_category_options,
);
return $form['eyfs_category_wrapper'];
}
The wrapper should be the id of the element to replace. you have it as a class for eyfs_category_wrapper
plus I'm not sure if 'eyfs_category_wrapper' is a valid element, normally I use a field set, or just add a prefix and suffix to my target field.
Related
I started fiddling with Prestashop 1.7 modules and I ran into this weird behavior.
I have this code to save values from form post to database (working ok)
protected function postProcess()
{
$form_values = $this->getConfigFormValues();
foreach (array_keys($form_values) as $key) {
Configuration::updateValue($key, Tools::getValue($key));
if($key == 'MSLT_MEGAMENU_CATEGORIES'){
$categories = implode(",",Tools::getValue($key));
Configuration::updateValue('MSLT_MEGAMENU_CATEGORIES', $categories);
}else{
$this->errors[]=$this->l('Please select categories to display');
}
}
}
And I use this code to fetch those values from database (works ok)
protected function getConfigFormValues()
{
$categories = explode(',',Configuration::get('MSLT_MEGAMENU_CATEGORIES', true));
return array(
'MSLT_MEGAMENU_LIVE_MODE' => Configuration::get('MSLT_MEGAMENU_LIVE_MODE', true),
'MSLT_MEGAMENU_CATEGORIES' => $categories,
'MSLT_MEGAMENU_ACCOUNT_EMAIL' => Configuration::get('MSLT_MEGAMENU_ACCOUNT_EMAIL', 'contact#prestashop.com'),
'MSLT_MEGAMENU_ACCOUNT_PASSWORD' => Configuration::get('MSLT_MEGAMENU_ACCOUNT_PASSWORD', null),
);
}
and helper to populate form with values
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs */
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
return $helper->generateForm(array($this->getConfigForm()));
This is the var_dump() when trying to load values from database, for this case my DB value is (1,3,9)
array(1) { [0]=> string(1) "9" }
As you can see Configuration::get() only gets the last string value.
Interesting behavior is that when I update the data and stay in the same page, then everything is ok and data is fetched properly, but when I leave module configuration page and comeback, the issue happens. Maybe I am missing some little snippet of code? I am still a newbie. If needed I can provide more code.
I don't know what your specific goal is but in any case it is always convenient to use Prestashop's own functions.
To save and select the configuration variables
eg, save values in json format
Configuration::updateValue('MYVALUES', Tools::jsonEncode(Tools::getValue('MYVALUES')), true );
eg, get values
Tools::jsonDecode( Configuration::get( 'MYVALUES' );
Dirty workaround I found to get imploded values from DB correctly. Maybe someone will use it.
$sql = 'SELECT * FROM '._DB_PREFIX_.'configuration WHERE name = "MSLT_MEGAMENU_SELECTED_CAT"';
$value = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
$selected = explode(',',$value['value']);
I have problem,when I tried to update except row of null in CakePHP.
Model -> Spot
column -> name,address
[MySQL]
id / name / address
1 / Shibuya Bakery / Shibuya street 123
For example,there is database like the one above.
Then CakePHP got a name-value(Shibuya Cake Shop) from Android,and address-value is null.
Therefore I wanna update just name-column.
id = 1(post from Android)
public function update()
{
if( isset($this->request->data["id"]) )
{
$id = intval($this->request->data["id"]);
$fields = array( 'Spot.id' => $id );
$data = array( 'Spot.name' => "'".$this->request->data["name"]."'",
"Spot.address" => "'".$this->request->data["address"]."'");
$this->Spot->updateAll( $data,$fields );
}
}
If you just want to update just one field, just use saveField.
$this->Spot->id = $this->request->data['id'];
$this->Spot->saveField('name', $this->request->data['name']);
Don't use updateAll, as that is meant for updating multiple records, though technically you could add conditions to prevent it from doing so. You're also passing incorrect arguments into updateAll. (See http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-updateall-array-fields-mixed-conditions for the correct way.) If you want to update multiple fields at once on a single record, use save:
public function update()
{
if( isset($this->request->data["id"]) )
{
$fields = array('name');
if(!empty($this->request->data['address'])) array_push($fields, 'address');
$this->Spot->save($this->request->data, true, $fields);
}
}
Read more on saving: http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-your-data
OK, this is the situation. In my beforeSave function I want to manipulate some $this->request->data entries.
This is my component:
<?php
App::uses('Component', 'Controller');
class GetStationComponent extends Component {
public function getStationId ($station) {
$stationInstance = ClassRegistry::init('Station');
$conditions = array('OR' => array(
array('Station.code LIKE' => $station),
array('Station.naam LIKE' => $station),
array('Station.naam_overig LIKE' => $station)
));
$result = $stationInstance->find('list', array('conditions'=>$conditions));
$value = array_values($result);
$value = $value[0];
return $value;
}
}
?>
And this is my beforeSave function in my Controller:
public function beforeSave($options = array()) {
if (!empty($this->request->data['Experience']['vertrekstation']) && !empty($this->request->data['Experience']['aankomststation'])) {
$this->request->data['Experience']['vertrekstation'] = $this->GetStation->getStationId($this->request->data['Experience']['vertrekstation']);
$this->request->data['Experience']['aankomststation'] = $this->GetStation->getStationId($this->request->data['Experience']['aankomststation']);
}
return true;
}
It should return an ID of the stations name. But in the Database the name itself is stored (which is filled in by the user) instead of the ID. What do I need to change in my Component (I guess...) to return the right values?
(P.S. The query itself in the component returns an ID, because at first I'd put the 'beforeSave' directly into my function which saves the data, but then my validation error said that it wasn't a right value. Which is correct...)
To complement the other answers; to get just the value of a single field, use Model::field()
return $stationInstance->field('id', $conditions);
It is best to add a sort order to this statement to make sure that the results will always be returned in the same order:
return $stationInstance->field('id', $conditions, 'code ASC');
Since you only perform a single query on the Model, and don't do anything afterwards, you don't even need the intermediate $stationInstance variable. Your code can be further simplified to:
return ClassRegistry::init('Station')->field('id', $conditions, 'code ASC');
Some observations
Because of the 'fuzzy' matching on the name of the station, the first result may not always be the station intended by the user it's best to offer an 'autocomplete' functionality in your front-end and have the user pick the correct station (e.g. To prevent picking Den Haag when the user meant Den Haag HS)
If the station does not fully matches a station, you should present a warning that the station wasn't found
You didn't surround your search-terms with % for the LIKE queries. If you intend to search for 'name "contains", you should use '%' . $station . '%'. For "starts with" use $station . '%'
As #mark suggested; beforeSave() is a callback of the Model and should be located there.
Also; beforeSave() is triggered after validation has taken place, so it will probably be too late. beforeValidate() is the best callback for this
If the Experience model is already attached to the Station model, you don't need to use a component, because you can directly access the Station model. It's best to put the search-method inside the Station model;
Moving it all to the right(*) location
*) Other options are always possible, this is just a possible approach
Add the 'search' method to the Station-model;
app/Model/Station.php
public function getStationIdByName($name)
{
$name = trim($name);
if (empty($name)) {
return null;
}
$name = '%' . $name . '%';
$conditions = array(
'OR' => array(
array($this->alias . '.code LIKE' => $name),
array($this->alias . '.naam LIKE' => $name),
array($this->alias . '.naam_overig LIKE' => $name),
)
);
return $this->field('id', $conditions, 'code ASC');
}
..and use it in the Experience Model
app/Model/Experience.php
public function beforeValidate(array $options = array())
{
if (
!empty($this->data[$this->alias]['vertrekstation'])
&& !empty($this->data[$this->alias]['aankomststation'])
) {
// Directly access the Station-model from within the Experience Model
$this->data[$this->alias]['vertrekstation']
= $this->Station->getStationIdByName($this->data[$this->alias]['vertrekstation']);
$this->data[$this->alias]['aankomststation']
= $this->Station->getStationIdByName($this->data[$this->alias]['aankomststation']);
}
// Call parent-callback after setting the values
return parent::beforeValidate($options);
}
[UPDATE] Using the Conventions, prevent unwanted behavior
After writing the previous example, I noticed there are some flaws in your current setup;
If vertrekstation and aankomststation should hold the 'foreign key' of the station (the station-id) they are not named according to the CakePHP Model and Database Conventions
Because of 1) By putting this code inside the beforeValidate(), it will also be triggered when updating an existing record. Because you're using the aankomststation and vertrekstation field both to hold the name of the station (inside the Form) and the id (inside the database), the Model will attempt to look-up the station-id via the id when updating. NOTE that inside the form you'll still be using vertrekstation and aankomstation as field-name. These field names are not present in your database, and therefore will not be able to directly update data inside your database, that's where the beforeValidate() callback is used for
Because the Experience model needs two relations to the Station model (once as departure station ('vertrekstation'), once for arrival station ('aankomststation')), you will need an alias for the Station-model. See: Multiple relations to the same model
app/Model/Experience.php
class Experience extends AppModel {
/**
* Station will be associated to the 'Experience' Model TWICE
* For clarity, using an 'alias' for both associations
*
* The associated Models will be accessible via;
* $this->DepartureStation
* $this->ArrivalStation
*
* To stick to the CakePHP conventions, name the foreign keys
* accordingly
*/
public $belongsTo = array(
'DepartureStation' => array(
'className' => 'Station',
'foreignKey' => 'departure_station_id',
),
'ArrivalStation' => array(
'className' => 'Station',
'foreignKey' => 'arrival_station_id',
)
);
public function beforeValidate(array $options = array())
{
// vertrekstation and aankomststation hold the 'names' of the
// stations and will only be present if the form has been submitted
if (
!empty($this->data[$this->alias]['vertrekstation'])
&& !empty($this->data[$this->alias]['aankomststation'])
) {
// Directly access the Station-model from within the Experience Model
// using the *aliases*
$this->data[$this->alias]['departure_station_id']
= $this->DepartureStation->getStationIdByName($this->data[$this->alias]['vertrekstation']);
$this->data[$this->alias]['arrival_station_id']
= $this->ArrivalStation->getStationIdByName($this->data[$this->alias]['aankomststation']);
// Invalidate the vertrekstation and aankomststation fields if lookup failed
if (empty($this->data[$this->alias]['departure_station_id'])) {
// Unable to find a station. Mark the Form-field invalid
$this->invalidate('vertrekstation', __('A station with this name was not found'));
}
if (empty($this->data[$this->alias]['arrival_station_id'])) {
// Unable to find a station. Mark the Form-field invalid
$this->invalidate('aankomststation', __('A station with this name was not found'));
}
}
// Call parent-callback after setting the values
return parent::beforeValidate($options);
}
}
The find('list') option of Cake returns an array like
array( 1 => 'name1',
3 => 'name2',
//etc...
)
where the index is the id and the value is the display field you set on the model.
So, when you do $value = array_values($result);, you're extracting the values of the array (meaning, the display fields). I'm assuming you're not using the id as the displayField, so that's why it's returning the names and not the id.
I'm not sure why you're using find('list') instead of find('first') or other alternative, but if you don't want to modify that for whatever reason, the fix that should return the first id obtained by the search is
reset($result); //possibly not needed, but just in case
$value = key($result );
First you must understand how Cake works
There is no $this->request in your models. Its part of the controller.
In your model your passed data will be in $this->data directly.
public function beforeSave($options = array()) {
parent::beforeSave($options); // you also forgot the parent call
if (!empty($this->data[$this->alias]['vertrekstation']) && ...)) {
$this->data[$this->alias]['vertrekstation'] = ...;
}
return true;
}
Your find call also looks pretty screwed up. I dont know what you want to do.
But I strongly advice you to use debug() etc to find out what is returned and correct your code accordingly.
You probably need find(first) if you are only interesting in a single value.
well i'm confused on how to insert "Checkboxes" values to SQL
here's my code
$form['last'] = array(
'#type' => 'checkboxes',
'#title' => "Just title",
'#options' => array(
'opt1' => "Option 1",
'opt2' => "Option 2",
),
as you can see my form consist of two checkbox, so how to get the value and insert to sql language. anyone can give an example or hint
here the method that i'm used to get the value (i know its very wrong)
function fasil_form_submit($form,&$form_state){
global $user;
$entry = array(
'uid' => $user->uid,
'test1' => $form_state['values']['1first'],
$jenis = 'aa_test';
$return = insert_form($entry,$jenis);
}
ps : sorry for my bad english
I'm not 100% sure what you're trying to do but I think you're trying to insert a value in the database for each of the checkboxes ticked? If so this is the quickest way:
function fasil_form_submit($form,&$form_state){
// Filter out un-checked items
$checked = array_filter($form_state['values']['last']);
global $user;
foreach ($checked as $value) {
$entry = array(
'uid' => $user->uid,
'test1' => $value
);
$jenis = 'aa_test';
insert_form($entry, $jenis);
}
}
As already mentioned in another answer the simplest way to see what you need to get from the form is to output $form_state['values'] in your submission function to see what was passed from the form.
However, rather than use the unsightly print_r and potentially messing up the form submission by calling exit prematurely (in Drupal 7 drupal_exit() should always be used instead of exit anyway), I strongly recommend you download and install the Devel module and use it's dpm() function to print the variable to the screen.
Any variable passed to dpm() is outputted to the standard Drupal messages area, and becomes an easy to navigate on-screen hierarchy of that variable like this:
You can use it absolutely anywhere in code within Drupal, e.g.
function fasil_form_submit($form,&$form_state){
// Output the form submission array to the messages area:
dpm($form_state['values']);
}
The Devel module is very good, and absolutely essential for any serious Drupal development.
Hope that helps.
Here's a quick way I like to look at my form output
function fasil_form_submit($form,&$form_state){
header('content-type: Text/plain');
print_r($form_state['values']);
exit;
global $user;
$entry = array(
'uid' => $user->uid,
'test1' => $form_state['values']['1first'],
$jenis = 'aa_test';
$return = insert_form($entry,$jenis);
}
Now those 3 lines should make it clear how Drupal is submitting the data.
I believe you will need to loop through $form_state['values']['last'] and test that the key is not set to 0.
function fasil_form_submit($form,&$form_state){
global $user;
foreach ($form_state['values']['last'] as $key => $value) {
if (value != 0) {
// $form_state['values']['last'][$key] was checked
}
else {
// $form_state['values']['last'][$key] not checked
}
}
}
I have a small problem. I am making a site that has Tags and Questions. I have a Question model, Tag model, QuestionsTag model, everything fits together nicely. The user upon asking something puts the tags in the field seperated by a space (foo bar baz) much like on stackoverflow.com.
Now, here is the code to check if a tag already exists or not and entering the tag into the database and the required associations:
function create () {
if (!empty($this->data)) {
$this->data['Question']['user_id'] = 1;
$question = $this->Question->save ($this->data);
/**
* Preverimo če se je vprašanje shranilo, če se je,
* vprašanje označimo.
*/
if ($question) {
$tags = explode (' ', $this->data['Question']['tags']);
foreach ($tags as $tag){
if (($tagId = $this->Tag->existsByName($tag)) != false) {
/**
* Značka že obstaja, torej samo povezemo trenuten
* id z vprašanjem
*/
$this->QuestionsTag->save (array(
'question_id' => $this->Question->id,
'tag_id' => $tagId
));
}
else {
/**
* Značka še ne obstaja, jo ustvarimo!
*/
$this->Tag->save (array(
'name' => $tag
));
// Sedaj pa shranimo
$this->QuestionsTag->save(array(
'question_id' => $this->Question->id,
'tag_id' => $this->Tag->id
));
$this->Tag->id = false;
}
; }
}
}
}
The problem is this, a Question has an id of 1 and I want it to have the tags with id of 1, 2, 3.
When the 2nd and 3rd save get called, Cake sees that in the questions_tags table is already a question with id 1, so it just updates the tag.
But this is not correct, as there should be many questions in that table with the same id, as they refer to different tags belonging to them.
So, is there a way to prevent this? Prevent the save method from UPDATEing?
Thank you!
This behavior isn't specific to HABTM relationships. You are calling the save() method inside of a loop. After the first save, an id value is set and each subsequent save call sees the id and assumes it's an update. Within a loop, you first need to call model->create() to reset an id value that may exist.
From the CakePHP Docs at http://book.cakephp.org/view/75/Saving-Your-Data:
When calling save in a loop, don't forget to call create().
In your case, it would look like this:
$this->QuestionsTag->create();
$this->QuestionsTag->save (array(
'question_id' => $this->Question->id,
'tag_id' => $tagId
));
Check out saveAll. You can make a single call to $this->Question->saveAll(), and it will save any associated data you supply as well. Note that with HABTM data, it will perform a DELETE for any questions_tags associated with that question_id, then perform an INSERT for all the tag_id's included with your data.
if you want to make sure, that a new entry (INSERT) is made rather then an update, you can set $this->create(); right in front of the save call. See http://book.cakephp.org/view/75/Saving-Your-Data (in the upper part of the page): When calling save in a loop, don't forget to call create().