I am new to javascript and Vue, I have made this simple form using CoreUI Vue and js and I submit the data on PostgreSQL.
In the code if I Use v-on:submit="postdata" it submits once and empty , if I use v-on:submit.prevent="postdata" it submits twice the first time empty and the second time right.
Please help I am stuck many days I can't find something wrong,
<template>
<div>
<CCard>
<CCardHeader>
<slot name="header"> <CIcon name="cibCcVisa" /> {{ caption }} </slot>
</CCardHeader>
<CForm id="myforma" v-on:submit="postdata">
<CCardBody>
<CRow>
<CCol>
<CInput name="title" label="title" placeholder="Enter Title" v-model="posts.title" id="title" />
</CCol>
</CRow>
<CRow>
<CCol>
<CInput label="year" type="date" v-model="posts.year" name="year" />
</CCol>
</CRow>
<CRow>
<CCol>
<CInput name="writer" label="writer" placeholder="Enter the writer" :v-model="posts.writer" />
</CCol>
</CRow>
<CRow>
<CCol sm="12">
<CInput name="description" label="description" placeholder="Write the description" v-model="posts.description" />
</CCol>
</CRow>
<CRow>
<CCol lg="6">
<CSelect label="type" name="type" :options="['1.Books', '2.Comics', '3.NOvels', '4.Writings']" :value.sync="posts.type" />
</CCol>
</CRow>
</CCardBody>
<CCardFooter>
<CButton type="submit" size="sm" color="primary"><CIcon name="cil-check-circle" /> Submit</CButton>
<CButton type="reset" size="sm" color="danger"><CIcon name="cil-ban" /> Reset</CButton>
</CCardFooter>
</CForm>
</CCard>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'forma',
data(){
return{
posts: {
title: '',
year :'' ,
writer:null,
description:null,
type: '1.Books'
},
}
},
props: {
caption: {
default: 'Thanasis Form'
}
},
methods: {
postdata() {
axios.post('http://localhost/post.php',this.posts).then((response) => {this.posts= response.data;
console.log(response.data)});
console.log(this.posts);
}
}
}
</script>
<style></style>
<?php
include "db.php";
$received_data = json_decode(file_get_contents("php://input"),true);
$table= $received_data['title'];
$wri=$received_data['writer'];
$result=pg_query($connection,"INSERT INTO tablet (title) VALUES (' $table')");
?>
Related
I have added a q-select And I gate my form a submit event. Submit event not working when there is a q-select.But without the q-select it is working.
<q-form #submit.prevent="addNewRole" class="q-gutter-md">
<q-input
v-model="newRoleForm.name"
type="text"
autofocus
label="Role Name"
color="info"
required
/>
<q-select
v-model="newRoleForm.accessLevel"
:options="accessTypes"
label="Access Level"
color="info"
/>
<q-btn
class="q-mt-lg"
color="primary"
icon="add_moderator"
label="Add Role"
/>
</q-form>
<script setup>
const addNewRole = () => {
alert("works");
};
</script>
You should remove the .prevent modifier, set the type of the button to submit, add a rules prop to the q-input and define the binded data:
<template>
<q-form class="q-gutter-md" #submit="addNewRole">
<q-input
v-model="newRoleForm.name"
type="text"
autofocus
label="Role Name"
color="info"
:rules="[ruleRequired]"
/>
<q-select
v-model="newRoleForm.accessLevel"
:options="accessTypes"
label="Access Level"
color="info"
/>
<q-btn
type="submit"
class="q-mt-lg"
color="primary"
icon="add_moderator"
label="Add Role"
/>
</q-form>
</template>
<script>
export default
{
data()
{
return {
newRoleForm:
{
name: '',
accessLevel: null,
},
};
},
computed:
{
accessTypes()
{
return [
{
value: 'full',
label: 'Full access',
},
{
value: 'restricted',
label: 'Restricted access',
},
];
},
},
methods:
{
ruleRequired(val)
{
return typeof val === 'number' ? true : (Array.isArray(val) ? val.length > 0 : !!val) || 'Required field';
}
}
}
</script>
Add type submit for the button, also remove prevent from #submit.prevent
<q-btn
type="submit"
class="q-mt-lg"
color="primary"
icon="add_moderator"
label="Add Role"
/>
I am using React popper for displaying additional information for input fields in my form. The problem is that, when i am displaying Tooltip for more than 1 element, it displays the same tooltip. How can i display different tooltips for each field.
Here is the code i am using inside my Component
https://codesandbox.io/s/hungry-gould-modgk?fontsize=14&hidenavigation=1&theme=dark
// Popper Tooltip Props;
const {
getArrowProps,
getTooltipProps,
setTooltipRef,
setTriggerRef,
visible,
} = usePopperTooltip({
trigger: 'hover',
placement: 'right',
closeOnOutsideClick: false,
visible: controlledVisible,
onVisibleChange: setControlledVisible
})
return (
<TextBox
label="Title"
className="title-field"
name="title"
type="text"
isRequired={true}
/>
<div className="field-info" ref={setTriggerRef}>
<Icon size="medium">
<FontAwesomeIcon icon={faInfoCircle} size="lg" />
</Icon>
</div>
{visible && (
<div
ref={setTooltipRef}
{...getTooltipProps({ className: 'tooltip-container' })}
>
Tooltip element
<div {...getArrowProps({ className: 'tooltip-arrow' })} />
</div>
)}
<TextBox
label="Price"
className="price-field"
name="price"
type="text"
isRequired={true}
/>
<div className="field-info" ref={setTriggerRef}>
<Icon size="medium">
<FontAwesomeIcon icon={faInfoCircle} size="lg" />
</Icon>
</div>
{visible && (
<div
ref={setTooltipRef}
{...getTooltipProps({ className: 'tooltip-container' })}
>
Tooltip element
<div {...getArrowProps({ className: 'tooltip-arrow' })} />
</div>
)}
)
[1]: https://i.stack.imgur.com/oHuBA.png
Each tooltip needs its own visible state variable. Can you create your own tooltip component like so:
const MyTooltip = ({tooltipText}) => {
const [isVisible, setIsVisible] = useState(false)
const {
getArrowProps,
getTooltipProps,
setTooltipRef,
setTriggerRef,
visible,
} = usePopperTooltip({
trigger: 'hover',
placement: 'right',
closeOnOutsideClick: false,
visible: isVisible,
onVisibleChange: setIsVisible
})
return (
<>
<div className="field-info" ref={setTriggerRef}>
<Icon size="medium">
<FontAwesomeIcon icon={faInfoCircle} size="lg" />
</Icon>
</div>
{visible && (
<div
ref={setTooltipRef}
{...getTooltipProps({ className: 'tooltip-container' })}
>
{tooltipText}
<div {...getArrowProps({ className: 'tooltip-arrow' })} />
</div>
)}
</>
)
}
Then you can use the component like this:
<TextBox
label="Title"
className="title-field"
name="title"
type="text"
isRequired={true}
/>
<MyTooltip tooltipText="Tooltip Element 1" />
<TextBox
label="Price"
className="price-field"
name="price"
type="text"
isRequired={true}
/>
<MyTooltip tooltipText="Tooltip Element 2" />
I'm working on a form to create a new product and I need a row with 3 equals fields but I'm not getting there using React Semantic Ui.
How can I code 3 equal input fields using react semantic ui?
That's what I've tried:
import { Form, Input, Button, TextArea, Header, Icon } from "semantic-ui-react";
function CreateProduct() {
return (
<>
<Header as="h2" block>
<Icon name="add square" color="violet" />
Cadastrar Produto
</Header>
<Form>
<Form.Group widths="equal">
<Form.Field
control={Input}
name="name"
label="Nome"
placeholder="Nome do Produto"
/>
<Form.Field
control={Input}
name="price"
label="Preço"
placeholder="Preço"
min="0.00"
step="0.10"
type="number"
/>
<Form.Field
control={Input}
name="media"
type="file"
label="Imagem"
accept="image/*"
content="Escolha Imagem"
/>
</Form.Group>
<Form.Field
control={TextArea}
name="description"
label="Descrição"
placeholder="Descrição do Produto"
/>
<Form.Field
control={Button}
inverted
color="violet"
icon="pencil alternate"
content="Cadastrar"
type="submit"
/>
</Form>
</>
);
}
export default CreateProduct;
The output that I am getting is:
See the 3rd input "Imagem"?
It seems that the field is not following the Form.Group props widths='equal' from semanctic-react-ui document
This layout is exceed because of the file type content.
May be you can try this way to get that layout
import React, { Component } from "react";
import { Form, Input, Button, TextArea } from "semantic-ui-react";
class FormExample extends Component {
fileInputRef = React.createRef();
render() {
return (
<Form>
<Form.Group widths="equal">
<Form.Field
control={Input}
name="name"
label="Nome"
placeholder="Nome do Produto"
/>
<Form.Field
control={Input}
name="price"
label="Preço"
placeholder="Preço"
min="0.00"
step="0.10"
type="number"
/>
<Form.Field>
<label>Imagem</label>
<Button
style={{ width: "100%" }}
content="Choose File"
labelPosition="left"
icon="file"
onClick={() => this.fileInputRef.current.click()}
/>
<input
ref={this.fileInputRef}
type="file"
hidden
onChange={this.fileChange}
/>
</Form.Field>
</Form.Group>
<Form.Field
control={TextArea}
name="description"
label="Descrição"
placeholder="Descrição do Produto"
/>
<Form.Field
control={Button}
inverted
color="violet"
icon="pencil alternate"
content="Cadastrar"
type="submit"
/>
</Form>
);
}
}
export default FormExample;
demo : https://codesandbox.io/s/zen-frost-9ihqw (adjust the screen size for full view)
I found a good solution just adding the "Fluid" props on the second .
<Form.Field
fluid
control={Input}
name="price"
label="Preço"
placeholder="Preço"
min="0.00"
step="0.10"
type="number"
/>
I am new to Redux. I've learned React and trying to learn Redux. I am building a todo app with Redux. I am managed to create, read and delete todos, but I am not managed to edit the todo.
My code: AddTodoForm
<FormGroup>
<Label for="title">Title</Label>
<Input type="text" name="title" id="title" placeholder="Enter Title" onChange={this.handleChange.bind(this)} /> {/* <input type="text" value={this.state.value} onChange={this.handleChange.bind(this, 'title')} /> */}
</FormGroup>
<FormGroup>
<Label for="description">Description </Label>
<Input type="textarea" name="description" id="description" onChange={this.handleChange.bind(this)} />
</FormGroup>
<FormGroup>
<div>
<CustomInput className="toggleInput" type="checkbox" data-toggle="toggle" id="exampleCustomCheckbox" label="Do You want to add Reminder??" onChange={this.toggle.bind(this, !this.state.checkBoxToggle)} />
</div>
</FormGroup>
{this.state.checkBoxToggle ?
<FormGroup>
<Label for="reminder">Reminder </Label>
<Input type="datetime-local" name="date" defaultValue={moment(Date.now()).format( 'YYYY-MM-DDTHH:mm')} id="date" onChange={this.handleChange.bind(this)} />
</FormGroup>
: ''}
<FormGroup check row>
<Col className="text-center">
<Button className="btn btn-success" onClick={this.handleSubmit.bind(this)}>Submit</Button>
</Col>
</FormGroup>
My handleChange function, where I set states of input:
handleChange(e) {
console.log(e.target.value, e.target.name);
if (e.target.name == "date") {
console.log('date is', e.target.value, new Date(e.target.value).valueOf());
this.setState({
[e.target.name]: new Date(e.target.value).valueOf()
})
} else {
this.setState({
[e.target.name]: e.target.value
})
}
}
This the render list function, where I want to edit my todo, but I am not able to edit the todo. I am able to delete, but not edit:
renderList() {
if (this.props.todos) {
return _.map(this.props.todos, (todo, id) => {
return (
<tr key={id + 1}>
<th scope="row">{id + 1}</th>
<td><Input type="text" disabled name="title" id="title" value={todo.title} onChange={this.handleChange.bind(this)} /></td>
<td><Input type="textarea" value={todo.description ? todo.description : this.state.description} name="description" id="description" onChange={this.handleChange.bind(this)} /></td>
<td>{todo.reminder}</td>
<td> <button className='btn btn-danger' onClick={this.onDeleteClick.bind(this, todo._id)}>Delete</button></td>
<td><button className='btn btn-success' onClick={this.markCompleted.bind(this, todo._id)}>Mark Complete</button></td>
</tr>
);
})
}
}
The specific todo, which I want to edit doesn't allow to type any value in the input box. I am not able to set it. Please let me know where I am doing wrong.
Don't reinvent the wheel. Instead of trying to reimplement form state, with event handlers, slice and reducers, use Redux Form.
It is made for that specific purpose and has an elegant, efficient API.
I am trying to populate a form with initial data however I am unsure of the syntax for this functionality and how it's suppose to be applied. initially the form I am using is a component that I also use to create a client. I am trying to reuse this form as the form for editing a client. It has two functions.
As per suggestions in Redux I have a this as a component and I also have a container.
Now, using the redux tool in Chrome I can look at the state and its clear the action has added an "editClient" entry with data so I do have the data. Its called "editClient" in the state.
My problem is that I do not know how to use this to set these state values as initial values. I have looked carefully at the docs but I am confused as to the way it should be stuctured.
Here is my client form in its entirety:
import React, { PropTypes } from 'react'
import { Field, reduxForm, FormSection } from 'redux-form'
import { connect } from 'react-redux'
import { Col, Row } from 'react-bootstrap'
import { Button, Glyphicon, Panel } from 'react-bootstrap'
import Moment from 'moment'
import Address from '../../address/addressContainer'
import FormField from '../../formComponents/formField'
import CheckboxField from '../../formComponents/checkboxField'
import TextField from '../../formComponents/textField'
import StaticText from '../../formComponents/staticText'
import TextAreaField from '../../formComponents/textAreaField'
import DateField from '../../formComponents/datefield'
import reducer from '../edit/reducer'
export const CLIENT_FORM_NAME = 'Client'
const required = value => (value ? undefined : 'Required')
const maxLength = max => value =>
value && value.length > max ? `Must be ${max} characters or less` : undefined
const number = value =>
value && isNaN(Number(value)) ? 'Must be a number' : undefined
const minValue = min => value =>
value && value < min ? `Must be at least ${min}` : undefined
const email = value =>
value && !/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)
? 'Invalid email address'
: undefined
const tooOld = value =>
value && value > 65 ? 'You might be too old for this' : undefined
const aol = value =>
value && /.+#aol\.com/.test(value)
? 'Really? You still use AOL for your email?'
: undefined
const normalizeMobilePhone = value => {
if (!value) {
return value
}
const onlyNums = value.replace(/[^\d]/g, '')
if (onlyNums.length <= 4) {
return onlyNums
}
if (onlyNums.length <= 8) {
return `${onlyNums.slice(0, 4)} ${onlyNums.slice(4)}`
}
return `${onlyNums.slice(0, 4)} ${onlyNums.slice(4, 7)} ${onlyNums.slice(7, 10)}`
}
export const Client = (props) => {
const {
handleSubmit,
companyValue,
isWarrantyCompanyValue,
isEditMode } = props
const { reset } = props
return (
<Row>
<Col md={12}>
<h2><Glyphicon glyph="edit" /> {isEditMode ? 'Edit' : 'New'} Client</h2>
<hr />
<form onSubmit={handleSubmit} className="form-horizontal">
{isEditMode && (
<Panel header={<h3>Client - Basic Details</h3>}>
<Row>
<Field component={StaticText}
name="clientNo"
id="clientNo"
label="Client No."
fieldCols={4}
labelCols={4}
controlCols={8}
/>
<Field component={StaticText}
name="dateCreated"
id="dateCreated"
label="Date Created."
fieldCols={4}
labelCols={4}
controlCols={8}
/>
<Field component={StaticText}
name="userName"
id="userName"
label="Created By."
fieldCols={4}
labelCols={4}
controlCols={8}
/>
</Row>
<Row>
<Field
component={props => {
return (
<StaticText {...props}>
<p
className="form-control-static"
>
<Glyphicon glyph={props.input.value ? 'ok' : 'remove'} />
{' '}{props.input.value ? 'Has jobs attached' : 'No jobs attached'}
</p>
</StaticText>
)
}}
name="activity"
id="activity"
label="Activity"
fieldCols={4}
labelCols={4}
controlCols={8}
/>
<Field component={CheckboxField}
name="active"
id="active"
label="De-Activate"
checkboxLabel="De activate this client"
fieldCols={4}
labelCols={4}
controlCols={8}
/>
</Row>
</Panel>
)}
<Panel header={<h3>Client - CompanyDetails</h3>}>
<Row>
<Field component={CheckboxField}
id="company"
name="company"
label="Company?"
checkboxLabel="Client represents a company"
fieldCols={6}
labelCols={3}
controlCols={9}
/>
</Row>
{companyValue && (
<div>
<Row>
<Field component={TextField}
name="companyName"
id="companyName"
type="text"
label="Company Name"
placeholder="Enter company name..."
fieldCols={6}
labelCols={3}
controlCols={9}
/>
<Field component={TextField}
name="abn"
id="abn"
type="text"
label="ABN."
fieldCols={6}
labelCols={3}
controlCols={5}
/>
</Row>
<Row>
<Field component={CheckboxField}
id="isWarrantyCompany"
name="isWarrantyCompany"
label="Warranty Company?"
checkboxLabel="Client represents a warranty company"
fieldCols={6}
labelCols={3}
controlCols={9}
/>
{isWarrantyCompanyValue && (
<Field component={CheckboxField}
id="requiresPartsPayment"
name="requiresPartsPayment"
label="Requires Parts Payment?"
checkboxLabel="We pay for parts"
fieldCols={6}
labelCols={3}
controlCols={9}
/>
)}
</Row>
<Row>
<Field component={TextField}
name="companyEmail"
id="companyEmail"
type="email"
label="Spare Parts Email."
placeholder="Enter spare parts email..."
fieldCols={6}
labelCols={3}
controlCols={9}
/>
</Row>
</div>
)}
</Panel>
<Panel header={<h3>Client - {companyValue ? 'Company Contact' : 'Personal'} Details</h3>}>
<Row>
<Field component={TextField}
name="clientFirstName"
id="clientFirstName"
type="text"
label="First Name."
placeholder="Enter first name..."
fieldCols={6}
labelCols={3}
controlCols={9}
validate={[required]}
/>
<Field component={TextField}
name="clientLastName"
id="clientLastName"
type="text"
label="Last Name."
placeholder="Enter last name..."
fieldCols={6}
labelCols={3}
controlCols={9}
/>
</Row>
<Row>
<Field component={TextField}
name="mobilePhone"
id="mobilePhone"
type="text"
label="Mobile No."
placeholder="Enter mobile No..."
fieldCols={6}
labelCols={3}
controlCols={5}
normalize={normalizeMobilePhone}
/>
<Field component={TextField}
name="phone"
id="phone"
type="text"
label="Phone No."
placeholder="Enter phone No..."
fieldCols={6}
labelCols={3}
controlCols={5}
/>
</Row>
<Row>
<Field component={TextField}
name="email"
id="email"
type="email"
label="Email."
placeholder="Enter email address..."
fieldCols={6}
labelCols={3}
controlCols={9}
/>
</Row>
</Panel>
<FormSection name="Address">
<Address />
</FormSection>
<Panel header={<h3>Notes</h3>}>
<Row>
<Field component={TextAreaField}
id="notes"
name="notes"
label="Notes."
placeholder="Enter notes here..."
fieldCols={12}
labelCols={1}
controlCols={11}
/>
</Row>
</Panel>
<Panel header={<h3>Client - Bank Details</h3>}>
<Row>
<Field component={TextField}
name="bankName"
id="bankName"
type="text"
label="Bank Name."
placeholder="Enter bank name..."
fieldCols={4}
labelCols={4}
controlCols={8}
/>
<Field component={TextField}
name="bsb"
id="bsb"
type="text"
label="BSB No."
placeholder="Enter BSB No..."
fieldCols={4}
labelCols={4}
controlCols={8}
/>
<Field component={TextField}
name="account"
id="account"
type="text"
label="Account No."
placeholder="Enter Account No..."
fieldCols={4}
labelCols={4}
controlCols={8}
/>
</Row>
</Panel>
<div className="panel-body">
<Row>
<Col xs={4}>
<Row>
<Col xs={8} xsOffset={4}>
<Button bsStyle="primary" type="submit" bsSize="small">
<Glyphicon glyph="ok" /> Submit
</Button>
{' '}
<Button type="reset" bsSize="small" onClick={reset}>
<Glyphicon glyph="ban-circle" /> Clear
</Button>
</Col>
</Row>
</Col>
</Row>
</div>
</form>
</Col>
</Row >
)
}
let ClientForm = reduxForm({
form: CLIENT_FORM_NAME,
})(Client)
ClientForm = connect(
state => ({
initialValues: state.editClient // pull initial values from client reducer
}),
{ reducer } // bind client loading action creator
)(Client)
export default ClientForm
I have added the following at the bottom as per the redux form example:
ClientForm = connect(
state => ({
initialValues: state.editClient // pull initial values from client reducer
}),
{ reducer } // bind client loading action creator
)(Client)
...wnd when I save it I get the following error.
Exception: Call to Node module failed with error: Error: Field must be inside a component decorated with reduxForm()
I believe I have not understood how to set the initial values.
Where have I gone wrong and what I need to do to make this take the state values and load them?
The parameter for the function that connect returns should be ClientForm instead of Client. Try this:
ClientForm = connect(
state => ({
initialValues: state.editClient // pull initial values from client reducer
}),
{ reducer } // bind client loading action creator
)(ClientForm)