[SalesForce] Unable to get value of String from Component to JS Controller

I have a custom object ToDoObj which has no fields ( I am using only the Name field from it) and I am trying to create a ToDo list type of functionality with this Object. Below is my code for Component and Controller:

Component:

 <aura:component controller="ToDoController">
    <aura:attribute name="list" type="ToDoObj__c[]" />
    <aura:attribute name="listItem" type="ToDoObj__c" />
    <aura:handler name="init" action="{!c.myAction}" value="{!this}" />

   <div class="container">
    <form class="form-for-list">
      <div class="if-field-is-req">
        <div class="only-one-inputfield">
          <ui:inputText aura:id="todoitemfield" label="Enter ToDo Item  "
                        class="to-do-item"
                        labelClass="to-do-item__label"
                        value="{!v.listItem.Name}"/>
         </div>
       </div>
      </form>
    </div>
      <ui:button label="Add To List" 
                       class="add-to-list"
                       labelClass="label"
                       press="{!c.createToDo}"/>
<div class="msg">
              <div id="list" class="row">
                 <aura:iteration items="{!v.list}" var="item">
                     <ui:inputCheckbox value="" /><ui:outputText value="{!item.Name}"/>
                  </aura:iteration>
              </div>
          </div> 
</aura:component>

Controller:

({
 myAction : function(component, event, helper) {
    var action = component.get("c.getToDos");
    action.setCallback(this, function(data) {
    component.set("v.list", data.getReturnValue());
});
$A.enqueueAction(action);
 },

createToDo : function(component, event, helper) {
 var todoItemField = component.find("todoitemfield");
   console.log('field is'+todoItemField);
 var todoItem = todoItemField.get("v.value");   
    console.log('item is '+todoItem);
    if(!todoItem || 0 === todoItem.length){
        todoItem.set("v.errors", [{message:"Enter a value!"}]);
    }
    else {
    todoItem.set("v.errors", null);
    var listItem = component.get("v.listItem");
    createtodo(component, listItem);
}
},
createtodo: function(component, listItem) {
this.upserttodo(component, listItem, function(a) {
    var list = component.get("v.list");
    list.push(a.getReturnValue());
    component.set("v.list", list);
    this.updateTotal(component);
  });
},
})

I tried to debug the same using console.log but I am getting null value for todoItem while todoItemField is being updated correctly in the variable (as far as I know – it comes as some value which is in some other format and doesnt show the actual fieldName or something). Can anyone tell me where I am going wrong in this!

Best Answer

You need to give the attribute a default value:

<aura:attribute name="listItem" type="ToDoObj__c" default="{ sobjectType: 'ToDoObj__c', Name: '' }"/>
Related Topic