joomla get post data - joomla

I'm creating joomla component and i have problem with accesing data from post
in one view i have 6 inboxes 3 of them are chandled by JTable class and thats good, but other 3 i want to process, my fields:
<input id="jform[team1_goals_players]" class="" type="hidden" name="jform[team1_goals_players]" value="2,2," aria-invalid="false">
<input id="jform_team1_goals" class="required" type="text" value="4" name="jform[team1_goals]" aria-required="true" required="required" aria-invalid="false">
first one is field that i want to process and second is chandled by JTable class by using
$sth = JRequest::get('team1_goals_players');
$sth is empty
where i should use JRequest to get that value and other 2

JRequest is deprecated in 2.5.
$jinput = JFactory::getApplication()->input;
$post = $jinput->get('jform', array(), 'array');
$sth = $post['team1_goals_players'];

$sth is empty because there is no variable like team1_goals_players in the form.You must try like this- first get jform and then read team1_goals_players from jform.
$post = JRequest::get('jform');
$sth = $post['team1_goals_players'];
More about JRequest.

Related

DRF: How to pass Foreign key Select options to show in the forms

I have the following
class Pet(models.Model):
name = models.CharField(max_length=200)
breed = models.ForeignKey(
"Breed",
on_delete=models.CASCADE,
)
Now i Have the serializer as:
class PetSerializer(serializers.ModelSerializer):
class Meta:
model = Pet
fields = "__all__
and viewset
class PetViewSet(viewsets.ModelViewSet):
queryset = Pet.objects.all()
serializer_class = PetSerializer
Now i am creating a simple form with name and select for breed
<form>
<label for="name">Name</label><br>
<input type="text" id="name" name="name"><br>
<label for="breeds">Choose a car:</label>
<select name="breeds" id="breeds">
<option value="1">Breed1</option>
<option value="2">Breed2</option>
<option value="3">Breed3</option>
<option value="4">Breed4</option>
...
</select>
</form>
Till now I was using Django forms. Which populate select fields automatically.
Since with DRF there is no such thing.
I have to write the form manually. So how to populate the select options
I am fine with ajax or reacts also.
It's not clear which technology you are using for the frontend. If you are using django template engine, you just need to override the get_context_data method in the view that's rendering this template (or add it to the context dictionary passed to the render() method if you are not using class-based views), to include breeds objects.
For example:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['breeds'] = Breeds.objects.all() # or customize the queryset
return context
Otherwise, if you are using a js framework like react or vue you have to do a request from your frontend to the breeds endpoint in order to retrieve a list of them (so you need a view exposing that resource). Than use a for loop inside the select tag iterating through the breeds object so you can use the property you need to populate the value attribute of the option tag.
Here an example using vue, assuming that you stored the response.json() a variable named breeds.
<form>
<label for="name">Name</label><br>
<input type="text" id="name" name="name"><br>
<label for="breeds">Choose a car:</label>
<select name="breeds" id="breeds">
<option
v-for="breed in breeds"
:key="breed.id"
:value="breed.id"
>{{ breed.name }}</option>
</select>
</form>
Note that I'm using breed.id as the value option tags, since ModelSerializer use pk by default to represent relationships.

How To Reset File input using livewire

does anybody knows how to reset my input type="file". I'm been using the $this->reset() to clear the property of the input type="file".
$this->reset(['type', 'name', 'institution', 'year', 'certification']);
If you don't need to use id for any other purposes you can render the input like this:
<input type="file" id="{{ rand() }}" >
Instead of using rand() you can also use some kind of counter or any other value that will change on every render. Different id will force livewire to completely replace the element with new one, thus empty. Just setting value="" won't help as input type="file" is immutable. This solution is taken from here
Here is a solution I found in TALL Stack Tips to remove filename from input field after uploading via Livewire.
https://talltips.novate.co.uk/livewire/livewire-file-uploads-using-s3#removing-filename-from-input-field-after-upload
The solution involves implementing a counter to regulate the input file id
To reset a file input in livewire I removed id from that input. And assign a null value to the value.
input without id
<label>Upload Image
<input type="file" wire:model="image" class="w-full">
</label>
to assign null value
$this->image = null;
input create two wire(wire:click and wire:model), It works.
livewire:
<input wire:click="fileClear('fileName')" wire:model="fileName" type="file" id="fileName" name="fileName" >
class:
public function fileClear($inputId)
{
$this->$inputId = "";
}
Clearing #AlexYokisama answer
Yes the easy way is using id as the following.
<input type="file" id="{{ $rand }}" >
And then in you livewire component you need to declare this public $rand
And you can use it safely in your reset function.
public $rand;
public function resetForm()
{
$this->rand++;
}

Retrieve dynamically generate check box array values in controller

in my html i can able to add more fields using jquery and the field am generating is check box array. i need to retrieve this in my controller.
so far i have tried
<input type="checkbox" value="1" name="washing[]" id="washing[]">
<input type="checkbox" value="1" name="dryclean[]" id="dryclean[]">
In controller
$clothtypeid = $request->input('clothtypeid');
$washing = $request->input('washing');
$pressing = $request->input('pressing');
for($i=0;$i<count($clothtypeid);$i++){
//in here how to test if the checkbox is ticked then value=1 else 0 ??
}
I expect if the checkbox is ticked then i have to make 1 else 0
Thanks in Advance
So I did a bit of digging and found this Tutorial which suggests;
Setting the input type to "checkbox" like you did there..
Keep the same name and include the '[]' at the end of the name attribute so that you have the following in your form;
<input type="checkbox" name="check_list[]" value="washing">
<input type="checkbox" name="check_list[]" value="dryclean">
Then in the controller you can get the value by doing the following;
if(!empty($request['check_list'])){
// Loop through array to get the checked values.
foreach($request['check_list'] as $item){
//do something here like;
if($item == 'washing'){ //make db operation or assign to a variable..}
else if($item == 'dryclean'){//make db operation}
}
}
This is a very basic example as you can see and I have to say that I haven't tested it yet but I believe it will work. Try it and give feedback.
EDIT: There is an answer here

Laravel 5.1, update multiple values from checked checkbox

In Laravel 5.1, I need to update multiple values from checked checkbox.
I can edit some registries from a table by clicking the edit button for each registry, and that button send me to the edit view
(This is de edit view for a single registry)
With the url: http://myapp/someroute/2246/edit where 2246 is some id.
Inside that edit I can update 4 fields. One of those fields is called "my state" and can have the values 1, 2 or 3.
Now, I have to make a multi select edit feature, where I can check every row of the table that I need to update simultaneously (each have the name=someid) and then click some button called "Validate", and update for evey row only 1 field, the my state field, and the new value will be always 1 (in the picture the values are string but thats only for the view).
The question is: how can I call the method update for every id that I'm selecting in the view? every input checkbox has it's own name which is the id of the registry that I will update.
The update method just validate some values from the view and then call some myeditmethod, but in this case I will jump the update and go directly to myedit which is someting like:
public function myedit(Request $request, $id) {
$obj = Self::findOrFail($id);
$obj->fk_id_comuna = $req['fk_id_comuna'];
$obj->fk_id_user = $usuario_id;
$obj->date = \Carbon\Carbon::now();
$obj->fk_id_my_state = $estado; //THIS IS THE ONLY FIELD THAT I WILL EDIT, ALWAYS WITH THE SAME VALUE `1`
$obj->save();
I was trying the make a form for that Validate button but I don't know how to handle multiple id in one call on the edit method.
<form action="{!! route('myroute.update', ['id' => [HERE, HOW CAN I PASS MULTIPLE ID FROM THE CHECKED CHECKBOX] ]) !!}" method="POST">
<input type="submit" class="btn btn-primary pull-right" value="Validar" />
</form>
I was thinking on a javascript function which collect in a array every checked checkbox name and call the myedit method directly, without the formof the view, could be?
About passing multiple values as one Request value.
Assume you have form like this:
<form method="post">
<input type="checkbox" name="options[]" value="foo"/>foo<br/>
<input type="checkbox" name="options[]" value="bar"/>bar<br/>
<input type="checkbox" name="options[]" value="buz"/>buz<br/>
<input type="submit" value="Submit" />
</form>
Your request('options') would be an array: ["foo", "bar", "buz"].
Than you can iterate over options using foreach.
Inside your update method you can go with:
foreach ($option as request('options')) {
//put your previous code here, so it'd be applied for every option
}
In JS I did this:
var optionsChecked = [];
$('.options:checkbox:checked').each( function(){
optionsChecked .push($(this).val());
});
Then in ajax:
$.ajax({
type: 'POST',
data: {'id': optionsChecked },
etc
Then in PHP:
$all = $request->input('id');
foreach ($all as $id){
//whole obj->* = *;
$obj->save();
}

How can I generate an empty class based on a table in CodeIgniter?

I have a table in codeigniter with the rows id, name, and email. I have one view that I have a form that looks something like this:
<input name='name' value='<?= $record->name; ?>' />
<input name='name' value='<?= $record->email; ?>' />
I'd also like to use the form on new and empty records. is there a way to use CodeIgniters db class to generate an empty stdClass with the structure of a db result, so that this code does not throw a bunch of notices & errors?
There's no default solution to this. You either have to populate the object yourself with all the (empty) properties or just check if the property exists.
<input name='name' value='<?= isset($record->email) ? $record->email : ''; ?>' />
Don't forget to run form_prep() on those values.
If you want to try this, you could create a dummy class.
class DB_Record {
function __get($prop) {
return isset($this->$prop) ? $this->$prop : NULL;
}
}
Then have your records be an instance of it:
$record = new DB_Record;
// fetch data from your database and assign to properties of $record
Then when an inaccessible property is accessed, it will just return NULL.
try this, where teams is a table name:
$r = new stdClass();
foreach ($this->db->field_data('teams') as $f) {
$r->{$f->name} = '';
}
I.E: teams is MySQL table with fields: TeamName, Location, State
$r will be Object like:
$r->TeamName = ''
$r->Location = ''
$r->State = ''
and so on.
the best thing i think you can do is like that you use the set_value function from the form_helper so that your code will be changed to :
<input name='name' value='<?= set_value('name', $record->name); ?>' />
<input name='email' value='<?= set_value('email',$record->email); ?>' />
you can read more about the form_helper at from_helper

Resources