Goal: on focusout event I want to auto populate html input fields #City #State (full name) #State2 (abbreviation)
Questions
1) how do I get the input passed to the function?
2) What do I need to do to populate the fields?
in resouces\ views: locale.blade.php
<div>
<input type="text" name="City" id="City" value="{{ $city }}">
<input type="text" name="State" id="State" value="{{ $state }}">
<input type="text" name="State2" id="State2" value="{{ $state2 }}">
<input type="text" name="Zip" id="Zip" value="{{ $zip }}"
wire:focusout="setlocale">
</div>
in App\Http\ LiveWire Locale.php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\State;
use Illuminate\Support\Arr;
class Locale extends Component
{
public $zip = "";
public $city = "";
public $state = "";
public $state2 = "";
public function setlocale()
{
$locale_arr=[];
$g = $this->zip;
dd($g); ################## its only returning "" in my dd(); ###################
$z = State::get()->where('zip',$g);
$city = $z->city;
$state = $z->state_name;
$state2 = $z->state2_id;
//TODO somehow render these variables in input fields.
}
public function render()
{
return view('livewire.locale');
}
}
in App\Models\ ** State**
class State extends Model
{
use HasFactory;
}
Tinker
>>> use App\Models\State
>>> $a = State::get()->where('zip','10001');
=> Illuminate\Database\Eloquent\Collection {#70820
all: [
2569 => App\Models\State {#35131
id: 2570,
zip: "10001",
lat: 40.7506,
lng: -73.9972,
city: "New York",
state_id: "NY",
state_name: "New York",
county_name: null,
timezone: null,
},
],
}
With Livewire, you have to bind the inputs to the properties of your class using wire:model. Livewire will then handle setting the value of your inputs to what you have in the component.
<div>
<input type="text" name="City" id="City" wire:model="city" />
<input type="text" name="State" id="State" wire:model="state" />
<input type="text" name="State2" id="State2" wire:model="state2" />
<input type="text" name="Zip" id="Zip" wire:model="zip" wire:focusout="setlocale" />
</div>
Then, instead of using wire:focusout, I recommend that you use a lifecycle-hook in the PHP class instead. So remove wire:focusout="setlocale" from your HTML, and add the following to your PHP class,
public function updated($field, $value)
{
if ($field === 'zip') {
$this->setlocale();
}
}
public function setlocale()
{
$zip = State::where('zip', $this->zip)->first();
$this->city = $zip->city;
$this->state = $zip->state_name;
$this->state2 = $zip->state2_id;
}
Related
How to upload a file and save it in Prestashop 1.7?
In ProductComments module I have a modal with a <form>:
post-comment-modal.tpl
<form id="post-product-comment-form" action="{$post_comment_url nofilter}" method="POST" enctype="multipart/form-data">
<div>
<div class="form-floating">
<input name="comment_title" type="text" class="form-control" placeholder="Title"/>
<label for="comment_title">Title</label>
</div>
<div class="form-floating">
<input name="customer_name" type="text" class="form-control" placeholder="Name"/>
<label for="customer_name">Name</label>
</div>
<div class="form-floating">
<textarea name="comment_content" class="form-control" placeholder="Review"></textarea>
<label for="comment_content">Review</label>
</div>
<input type="file" id="photo_input" name="photo_input" multiple> // I've added this field
<button type="submit">Send</button>
</div>
</form>
I've added there a <input type="file">.
This form is posted into ProductCommentsPostCommentModuleFrontController which extends ModuleFrontController
PostComment.php
class ProductCommentsPostCommentModuleFrontController extends ModuleFrontController
{
public function display()
{
$id_product = (int) Tools::getValue('id_product');
$comment_title = Tools::getValue('comment_title'); // Proper value
$comment_content = Tools::getValue('comment_content'); // Proper value
$customer_name = Tools::getValue('customer_name'); // Proper value
$criterions = (array) Tools::getValue('criterion');
$photo = Tools::getValue('photo_input'); // false
$file = $_FILES['photo_input']['name']; // null
// Validation
/** #var EntityManagerInterface $entityManager */
$entityManager = $this->container->get('doctrine.orm.entity_manager');
//Create product comment
$productComment = new ProductComment();
// Validation
$productComment
->setProductId($id_product)
->setTitle($comment_title)
->setContent($comment_content)
->setCustomerName($customer_name)
->setCustomerId($this->context->cookie->id_customer)
->setGuestId($this->context->cookie->id_guest)
->setDateAdd(new \DateTime('now', new \DateTimeZone('UTC')))
;
$entityManager->persist($productComment);
$this->addCommentGrades($productComment, $criterions);
$entityManager->flush();
$this->ajaxRender(
json_encode(
[
'success' => true,
'product_comment' => $productComment->toArray(),
]
)
);
}
Is there a way to extend this controller, and add a variable which holds a file upoaded by user by POST method?
I must save x2 the same data fields (nif and name) at the same time in the DB.
With 1 field (nif) it works perfectly and save x2 rows in the DB with different info, so the JSON works, but adding the 2th field (name) it just save the nif value in all the fields.
I don't understand so much the JSON and his syntax logic, but I think the problem is how I wrote it in the controller.
P.D. No, I can't put EnviarCurriculumPreguntas::create x2 in a row because that's not the purpose of this code, so I'm using a JSON instead.
EnviarCurriculum.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class EnviarCurriculum extends Model
{
protected $table = 'table';
protected $primaryKey = 'ID_table';
protected $fillable = [
'nif',
'name'
];
public function getRepeatedFields()
{
return json_decode($this->nif);
return json_decode($this->name);
}
}
EnviarCurriculumController.php
namespace App\Http\Controllers\enviarCurriculum;
use App\EnviarCurriculum;
use App\Configuracion;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class EnviarCurriculumController extends Controller
{
public function index()
{
return view('enviar_curriculum', ['EnviarCurriculum' => new EnviarCurriculum()]);
}
public function create()
{
return view('enviar_curriculum', ['EnviarCurriculum' => new EnviarCurriculum()]);
}
public function store(Request $request)
{
foreach (request('nif', 'name') as $val) {
EnviarCurriculum::create(['nif' => $val, 'name' => $val]);
}
}
}
enviar_curriculum.blade.php
<!DOCTYPE html>
<html lang="es">
<head>
...
</head>
<body>
<form action="{{ route("store") }}" method="POST">
#csrf
<div>
<input type="text" name="nif[]" id="nif">
<input type="text" name="name[]" id="name">
</div>
<br>
<div>
<input type="text" name="nif[]" id="nif">
<input type="text" name="name[]" id="name">
</div>
<input type="submit" class="btn btn-primary" value="Enviar">
</form>
</body>
</html>
you can't have input having the same name without being an array
<!DOCTYPE html>
<html lang="es">
<head>
...
</head>
<body>
<form action="{{ route("store") }}" method="POST">
#csrf
<div>
<input type="text" name="nif[]" id="nif">
<input type="text" name="name[]" id="name">
</div>
<br>
<div>
<input type="text" name="nif[]" id="nif">
<input type="text" name="name[]" id="name">
</div>
<input type="submit" class="btn btn-primary" value="Enviar">
</form>
</body>
</html>
Then in your store method loop the array inputs
public function store(Request $request)
{
$nifs = $request->input('nif', []);
$names = $request->input('name', []);
foreach ($nifs as $key => $nif) {
EnviarCurriculum::create(['nif' => $nif, 'name' => $names[$key]??'']);
}
}
Then fix your getRepeatedFields() method to return both decoded fields.
public function getRepeatedFields()
{
return [
'nifs' => json_decode($this->nif),
'names' => json_decode($this->name),
];
}
<input type="text" name="nif[]" id="nif">
<input type="text" name="name[]" id="name">
in name , nif only store the last inserted item please change it as array
I'm a newbie in OctoberCms and i don't have much knowledge in Laravel also. While self studying I face a request like this it's a Select if record exist query I need to read the database and look for the match and I'm really confuse.
This is my form in form.htm where I design my Form.
use Drufal\DynamicContentManager\Models\MembersVerification;
==
<form data-request="onSend" accept-charset="UTF8" enctype="multipart/form-data">
<div class="form-group">
<label>First Name:</label>
<input type="text" class="form-control" name="first_name" required>
</div>
<div class="form-group">
<label>Middle Name:</label>
<input type="text" class="form-control" name="middle_name">
</div>
<div class="form-group">
<label>Last Name:</label>
<input type="text" class="form-control" name="last_name" required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" >Submit</button>
</div>
</form>
and this my model
<?php namespace Drufal\DynamicContentManager\Models;
use Model;
use Input;
/**
* Model
*/
class MembersVerification extends Model
{
use \October\Rain\Database\Traits\Validation;
/*
* Disable timestamps by default.
* Remove this line if timestamps are defined in the database table.
*/
public $timestamps = false;
/**
* #var array Validation rules
*/
public $rules = [
];
/**
* #var string The database table used by the model.
*/
public $table = 'drufal_dynamiccontentmanager_members';
public function onSend(){
$fn = Input::get('first_name');
$mn = Input::get('middle_name');
$ln = Input::get('last_name');
$membertbl=$table::where('first_name', '=', $fn)->first();
if ($membertbl === null) {
echo"
<script>
alert('Successfully');
</script>
";
}else{
echo"NO RESULT";
}
}
}
Help the newbie please.
I think you missed the DB:: in your database request:
$users = Db::table('users')->where('votes', 100)->first();
Maybe this documentation will help you:
https://octobercms.com/docs/database/query#where-clauses
I have a problem.
I'm using a Form Request but also Vue on my form. My problem is that old('') variables does not work together with Vue v-model.
Here is an example of the input field.
<div class="form-group">
<label for="name">{{ trans('messages.name') }}</label>
<input type="text" name="name" v-model="name" id="name" value="{{ old('name') }}" class="form-control">
#if($errors->has('name'))
<span class="help">
{{trans('Validations.name')}}
</span>
#endif
</div>
If I remove the v-model="name" the {{ old('name') }} variable works.
This is the error i get from Vue in the browser.
<input v-model="name" value="asdasdasd">:
inline value attributes will be ignored when using v-model. Declare initial values in the component's data option instead.
vue file
<script>
import RangeSlider from './RangeSlider.vue';
export default {
components: {
RangeSlider,
},
props: ['fields'],
data() {
return {
name: '',
email: '',
phone: '',
loading: false,
errors: {},
};
},
methods: {
onSubmit() {
this.loading = true;
}
}
};
</script>
Vue does not allow you to initialise model data from the HTML, because Vue expects you to retrieve data from an API and set it from the Vue instance, which can be a pain when using it in conjunction with blade. The simplest way around this is to create a directive to make the init yourself:
Vue.directive('init', {
bind: function(el, binding, vnode) {
vnode.context[binding.arg] = binding.value;
}
})
Then use as:
<input type="text" name="name" v-model="name" id="name" v-init:name="'{{old('name')}}'" class="form-control">
Here's the JSFiddle: https://jsfiddle.net/0uvqmodc/
You should try this with the help of v-bind, which dynamically bind one or more attributes.
<input type="text" name="name" v-model="name" id="name" v-bind:value="old('name')" class="form-control">
However if you want to set an initial value to the input field, you can just set the data variable name as the value (old('name')) you want to set.
HTML
<input type="text" name="name" v-model="name" id="name" class="form-control">
JS
data() {
return {
name: 'oldValue',
email: '',
phone: '',
loading: false,
errors: {},
};
},
I am trying to take data that a user inputs into a form, created in blade, and transport that data to my controller. At that point I can use a function in my controller to write the data into MySQL.
Here is the code for the form which I have in my blade file.
<form action="{{ route("users") }}" method="post">
<input type ="form" id="firstname"> firstname </input> <br>
<input type ="form" id="lastname"> lastname </input> <br>
<input type="form" id="email"> email </input> <br>
<input type="form" id="userlevel"> userlevel </input> <br>
<input type="form" id="password"> password </input> <br>
<br> <br>
<button type="submit"> Submit
</button>
</form>
Here is the code in my controller which writes data into MySQL. The code works when I am using dummy data, instead of the $name and $lastname variables.
public function users()
{
$name = $_POST["firstname"];
$lastname = $_POST["lastname"];
DB :: table("newUsers") -> insertGetId
(
array("firstname" => $name, "lastname" => $lastname, "email" => "test")
);
return view("pages.users");
}
I am currently getting an error that says
Undefined index: firstname
Ideally what I want to happen is for whatever the user entered for firstname and lastname to be written into my MySQL table.
You need to add name attributes to your inputs and format them correctly they should look more like:
<input type="text" id="firstname" name="firstname"></input>
If you are placing 'firstname' between your openning and closing input tags for a placholder value use the placeholder attribute instead.
<input type="text" id="firstname" name="firstname" placeholder="first name"></input>
But do be warned the placeholder attribute doesnt work in older browsers
Also dont use $_POST laravel has built in ways of getting the values from your form.
Laravel 5
$request->input('firstname');
like this:
public function users(Request $request)
{
$name = $request->input('firstname'); // This is better than using $_POST
$lastname = $request->input('lastname');
DB :: table("newUsers") -> insertGetId
(
array("firstname" => $name, "lastname" => $lastname, "email" => "test")
);
return view("pages.users");
}
Notice, I have passed in Request $request like a variable in the method users. You will also need to add use Illuminate\Http\Request as Request; to the top of your class:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request as Request; //here
class MyController extends Controller
{
}
Laravel 4
Input::get('firstname');
Change your Form as follows:
<form action="{{ route("users") }}" method="post">
<input type ="form" name=firstname" id="firstname" placeholder="First name">
<input type ="form" name=lastname" id="lastname">
<input type="form" name="email" id="email">
<button type="submit"> Submit </button>
</form>
You've to provide the name attribute to your form fields.
And in the controller, you don't have to use $_POST anymore.
Just use:
public function users(Request $request)
{
$firstname = $request->input('firstname');
$lastname = $request->input('lastname');
DB :: table("newUsers") -> insertGetId(
array("firstname" => $name, "lastname" => $lastname, "email" => "test")
);
return view("pages.users");
}
You can access form data with $request->get('first_name'), for example.
To make it work, add name tags to your form inputs and catch data, for example, if you use store action:
function store(Request $request){
}
In this case you also can easily validate input data by using custom Reuqest classes:
https://laravel.com/docs/master/validation#form-request-validation